2012-04-07 80 views
15

我已经创建了一些文档,并设法做出一些简单的查询,但是我无法创建一个查询来查找只存在字段的文档。如何在MongoDB中检查字段是否存在?

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

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

现在我想查询,将带给所有的文件,其中在otherInfo文本中有一些东西。

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

所以我想检查text场的存在在otherInfo

我该如何做到这一点?

回答

50

您可以组合使用$exists运营商与.符号。在蒙戈壳裸查询应该是这样的:

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"}} 
0

查询中是否不会过滤掉所有带有文本值的元素,如下所示。

db.things.find({otherInfo:{$in: [text]}}); 

BasicDBObject query = new BasicDBObject(); 
query.put("otherInfo", new BasicDBObject("$in", "[text]")); 
var result = db.find(query); 
+0

感谢喜回答,我怎样才能在Java中做到这一点? – jan1 2012-04-07 20:06:51

+0

http://www.mongodb.org/display/DOCS/Java+Tutorial – 2012-04-07 20:11:47

相关问题