Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether a field exists or not in MongoDB?

Tags:

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?

like image 736
jan1 Avatar asked Apr 07 '12 19:04

jan1


People also ask

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

What is exist in MongoDB?

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 .

How do I search for text in a field in MongoDB?

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.

How do I make a field not null in MongoDB?

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.


1 Answers

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"}}
like image 86
Matt Avatar answered Sep 23 '22 13:09

Matt