2012-04-07 8 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 }}) 

그리고 자바의 테스트 케이스는 다음과 같이 수 :

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 –

관련 문제