MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Como posso verificar se um campo existe ou não no MongoDB?


Você pode usar o $exists operador em combinação com o . notação. A consulta simples no mongo-shell deve ficar assim:
db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})

E um caso de teste em Java poderia ser assim:
    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());

Saída:
1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}