Mongodb Query To select records that have a given key

Entries in my database

{"_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 with a given key.

For example, if I pass ln as a parameter to the request, it shuold returns all records in which ln is the key. Results will be

 {"_id":"1","fn":"sagar","ln":"Varpe"} {"_id":"1","ln":"ln1","score":"10"} {"_id":"1","ln":"ln2"} 
+46
mongodb
Jan 03 2018-11-11T00:
source share
3 answers

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

Through the MongoDB shell ...

 db.things.find( { ln : { $exists : true } } ); 
+82
Jan 03 2018-11-11T00:
source share

I had the same problem and

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

worked for me

+6
Sep 09 '14 at 7:09
source share
 db.collection.find({ ln: { $exists: true} }); 

The $ size operator matches any array with the number of elements specified by the argument. For example:

 db.collection.find({ ln: { $exists: true, $size: 0 } }); 

$ size does not accept ranges of values. To select documents based on fields with a different number of elements, create a counter field that you increase when adding elements to the field.

0
May 26 '17 at 5:51
source share



All Articles