如何检查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]}

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

Now I want a query that will bring all the documents where the text in otherInfo has something in it.

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

if there is no text, then the otherInfo will just be like that: "otherInfo":[]

所以我想检查是否存在文本 otherInfo 中的字段。

So I want to check the existence of the text field in otherInfo.

我该如何实现?

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

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

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

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

输出:

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