How can I check whether a field exists or not in MongoDB?
java, mongodb
Solution
You can use the `$exists` operator in combination with the `.` notation. The bare query in the mongo-shell should look like this:
db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})
And a test case in Java could look like this:
BasicDBObject dbo = new BasicDBObject();
dbo.put("name", "first");
collection.insert(dbo);
dbo.put("_id", null);
dbo.put("name", "second");
dbo.put("otherInfo", new BasicDBObject("text", "sometext"));
collection.insert(dbo);
DBObject query = new BasicDBObject("otherInfo.text", new BasicDBObject("$exists", true));
DBCursor result = collection.find(query);
System.out.println(result.size());
System.out.println(result.iterator().next());
Output:
1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}
Problem
I have created some documents and managed to make some simple queries but I can't create a query that would find documents where a field just exists. For example suppose this is a document: ``` { "profile_sidebar_border_color" : "D9B17E" , "name" : "???? ???????" , "default_profile" : false , "show_all_inline_media" : true , "otherInfo":["text":"sometext", "value":123]} ``` Now I want a query that will bring all the documents where the text in `otherInfo` has something in it. If there is no text, then the `otherInfo` will just be like that: `"otherInfo":[]` So I want to check the existence of the `text` field in `otherInfo`. How can I achieve this?