本文介绍了如何检查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"}}

这篇关于如何检查MongoDB中是否存在字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 14:31