Mongodb Query To select records having a given key

Mongodb

Mongodb Problem Overview


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"} 

Mongodb Solutions


Solution 1 - Mongodb

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

Via the MongoDB shell ...

db.things.find( { ln : { $exists : true } } );

Solution 2 - Mongodb

I had the same problem and

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

worked for me

Solution 3 - Mongodb

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 different numbers of elements, create a counter field that you increment when you add elements to a field.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagar VarpeView Question on Stackoverflow
Solution 1 - MongodbJustin JenkinsView Answer on Stackoverflow
Solution 2 - MongodbHADEELView Answer on Stackoverflow
Solution 3 - MongodbhelpdocView Answer on Stackoverflow