1

I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key. For example, let's suppose this is what's inside my collection

{ 'res1': 10 }
{ 'res2: 20 }

How can I query the collection using only the key 'res1', in order to get 10 ?

3 Answers 3

2

Not sure exaclty what you want, so... This is if you want all documents that have key res1 set:

db.collection.find({'res1': { $exists : true }})

And this is if you want all the documents that have key res1 set to 10:

db.collection.find({'res1': 10})

0
2

Ah, I guess I'm structuring my data all wrong, I should have something like this:

{ 'name': 'res1',
  'value': 10 }

Right?

1
  • Right - you can also use a fields specifier to get back only the value portion: db.collection.find({'name': 'res1'}, fields=['value'])
    – mdirolf
    Nov 16, 2009 at 16:13
1
> db.collection.find({'res1': 10}) # Returns a cursor.

In your case, find_one method will do the needful.

> db.collection.find_one({'res1': 10}) # Returns a document whose value is 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.