天天看点

java mongo exists_java – 如何在MongoDB中检查一个字段是否存在?

您可以结合使用$exists操作符.符号. mongo-shell中的裸机查询应如下所示:

db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})

Java中的测试用例可能如下所示:

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());

输出:

1

{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}