2012-04-07 11 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":[]

だから私はotherInfotextフィールドの存在を確認したいです。

どうすればこの問題を解決できますか?

答えて

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

+0

http://www.mongodb.org/display/DOCS/Java+Tutorial –

関連する問題