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?
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null . If <boolean> is false, the query returns only the documents that do not contain the field. [ 1] MongoDB $exists does not correspond to SQL operator exists .
In MongoDB, we can perform text search using text index and $text operator. Text index: MongoDB proved text indexes that are used to find the specified text from the string content. Text indexes should be either a string or an array of string elements.
Basically, we can use the $exists a method to implement the not null in MongoDB. When <boolean> is valid, $exists coordinates with the records that contain the field, including reports where the field esteem is invalid. In case <boolean> is bogus, the question returns just the records that don't contain the field.
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"}}
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