如何检查MongoDB中是否存在字段?

我已经创建了一些文档并设法进行了一些简单的查询,但是我无法创建一个查询来查找字段存在的文档。

例如,假设这是一个文档:

{ "profile_sidebar_border_color" : "D9B17E" , "name" : "???? ???????" , "default_profile" : false , "show_all_inline_media" : true , "otherInfo":["text":"sometext", "value":123]} 

现在我想要一个查询,它将带来otherInfo中的文本所在的所有文档。

如果没有文本,那么otherInfo将是这样的: "otherInfo":[]

所以我想检查otherInfo是否存在text字段。

我怎样才能做到这一点?

您可以将$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"}} 

in查询不会过滤掉具有文本值的所有元素,请参阅下文。

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

或者您可以使用:

  import static com.mongodb.client.model.Filters.exists; Document doc = (Document) mongoCollection.find(exists("otherInfo")).first(); 

您可以使用com.mongodb.QueryBuilder类来构建Matt的答案中提供的查询:

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