Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb Query To select records having a given key

Tags:

mongodb

The records in my database are

{"_id":"1","fn":"sagar","ln":"Varpe"}  {"_id":"1","fn":"sag","score":"10"}  {"_id":"1","ln":"ln1","score":"10"}  {"_id":"1","ln":"ln2"}  

I need to design a MongoDB query to find all records that have a given key.

For example, if I pass ln as a parameter to the query it shuold return all records in which lnis a key. The results would be

{"_id":"1","fn":"sagar","ln":"Varpe"}  {"_id":"1","ln":"ln1","score":"10"}  {"_id":"1","ln":"ln2"}  
like image 958
Sagar Varpe Avatar asked Jan 03 '11 05:01

Sagar Varpe


People also ask

How do I select a specific record in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I use $in in MongoDB?

MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array.


2 Answers

To find if a key/field exists in your document use the $exists operator.

Via the MongoDB shell ...

db.things.find( { ln : { $exists : true } } ); 
like image 161
Justin Jenkins Avatar answered Oct 14 '22 17:10

Justin Jenkins


I had the same problem and

db.coll.find({"mykey":{'$exists': 1}}) 

worked for me

like image 28
HADEEL Avatar answered Oct 14 '22 19:10

HADEEL