jan1
jan1

Reputation: 623

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

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?

Upvotes: 22

Views: 56034

Answers (4)

Piyush Khera
Piyush Khera

Reputation: 527

You can use the com.mongodb.QueryBuilder class to build a query provided in Matt's answer:

QueryBuilder queryBuilder = QueryBuilder.start("otherInfo.text").exists(true);
DBObject query = queryBuilder.get();
DBCursor dbCursor = collection.find(query);

Upvotes: 1

Cafta
Cafta

Reputation: 21

Or you can use:

import static com.mongodb.client.model.Filters.exists;

Document doc = (Document) mongoCollection.find(exists("otherInfo")).first();

Upvotes: 2

Mattias Josefsson
Mattias Josefsson

Reputation: 1197

Wouldn't the in query filter out all elements with the text value see below.

db.things.find({otherInfo:{$in: [text]}});

BasicDBObject query = new BasicDBObject();
query.put("otherInfo", new BasicDBObject("$in", "[text]"));
var result = db.find(query);

Upvotes: 0

Matt
Matt

Reputation: 17629

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

Upvotes: 61

Related Questions