How to search MongoDB data like JSON

Viewed 32

(Using Python and pymongo)

Say I have a MongoDB collection that looks like this:

"_id": {whatever},
"list of stuff" : ["entry1","entry2","entry3"],
"some number" : 12

How can I search the database and just get values from the entries? Whenever I do,

.find({"some number" : {"$exists : True}})

It still just gets the entire thing, (because I'm just checking if it has that key I think?) but I want to retrieve the value from "some number" to use. Like you would in JSON with Object["some number"]. How can I do this with MongoDB?

1 Answers

Use projection to specify the fields you wish to keep in the result set. This example excludes _id and list of stuff.

coll.find({"some number": {"$exists": True}},
          projection={"_id": False, "list of stuff": False})

The projection kwarg is documented with the find method

Related