pymongo "Projection" to exclude all fields and only get selected fields?


Using mongodb projection we can define which filed to include and which one to exclude.

like this :

data = db.Users.find_one({'username': user },{"_id":0,"password":0,"email":1}) 

This Query will exclude the _id and password fields and only include email ,

But is there a way to exclude all the fields present in a document and only fetch email and phone,

In smaller documents I can set the project value to 0 for the items I dont need but for larger documents , is there a way to automatically exclude all other fields/items and only get the ones that are required ?

>Solution :

The specific command/syntax you have provided actually is not valid:

> db.Users.findOne({'username': 'user' },{"_id":0,"password":0,"email":1})
MongoServerError: Cannot do inclusion on field email in exclusion projection

You can see the same failure in this playground example.

By default though, projection is going to do exactly what you want. From the documentation:

Return the Specified Fields and the _id Field Only
A projection can explicitly include several fields by setting the <field> to 1 in the projection document.

So if you replace the (invalid) "password":0 component of your projection with "phone":1 to make the command as follows:

data = db.Users.find_one({'username': user },{"_id":0,"phone":1, "email":1}) 

It will behave like you want. Demonstration in this playground example.

Leave a ReplyCancel reply