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

jan*_*an1 19 java mongodb

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

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

{  "profile_sidebar_border_color" : "D9B17E" , 
   "name" : "???? ???????" , "default_profile" : false , 
   "show_all_inline_media" : true , "otherInfo":["text":"sometext", "value":123]}
Run Code Online (Sandbox Code Playgroud)

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

如果没有文字,那么otherInfo意志就是这样:"otherInfo":[]

所以我想检查一下该text字段的存在otherInfo.

我怎样才能做到这一点?

Mat*_*att 55

您可以将$exists运算符与.表示法结合使用.mongo-shell中的裸查询应如下所示:

db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})
Run Code Online (Sandbox Code Playgroud)

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());
Run Code Online (Sandbox Code Playgroud)

输出:

1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}
Run Code Online (Sandbox Code Playgroud)