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 ln
is a key. The results would be
{"_id":"1","fn":"sagar","ln":"Varpe"} {"_id":"1","ln":"ln1","score":"10"} {"_id":"1","ln":"ln2"}
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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.
To find if a key/field exists in your document use the $exists operator.
Via the MongoDB shell ...
db.things.find( { ln : { $exists : true } } );
I had the same problem and
db.coll.find({"mykey":{'$exists': 1}})
worked for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With