2011-09-26 63 views
5

我有我的收藏記錄中,我希望獲取的ID爲1,但我得到的細節,而不是2倍的1如何查找mongodb中的匹配記錄?

db.mycollection.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}, { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]}) 

的人的詳細信息,則運行

> db.mycollection.findOne({"person.id":1},{"person.details":1,"_id":0}) 

結果是:

{ 
     "person" : 
       [ 
        { 
         "details" : 
         { 
         "name" : "Aswini", 
         "Age" : 10 
         } 
        }, 
        { 
         "details" : 
         { 
         "name" : "Mahesh", 
         "Age" : 11 
         } 
        } 
       ] 
    } 

但我需要如下:

{ 
    "person" : [ 
       { 
       "details" : { 
          "name" : "Aswini", 
          "Age" : 10 
         } 
       } 
      ] 
    } 

不明白我們在哪裏犯錯。請你需要你的幫助。我正在使用MongoDB,Java

回答

0

person是一個數組。如果你想獲得這個數組的第一個元素,你應該使用$slice

db.mycollection.findOne({"person.id":1},{"person":{$slice:[0,1]},"_id":0}) 
+0

其錯誤。 op不想要第一個元素,他想要檢索匹配的子數組,而不考慮位置。如果person.id子文檔位於查詢的最後位置,則不會發生這種情況 – RameshVel

+0

您是絕對正確的。我希望子數組與索引無關。如果你有任何解決方案是MongoDB的新手,請幫忙 – aswininayak

3

這是濾波的多層次嵌入文檔的行爲,通常是匹配濾波器將返回整個文檔,而不是子集。

通常positional operator $用於匹配updates中的子文檔。但該功能尚未在返回說明符中實現。

mongo Support for positional ($) operator in fields to return specifier已經有一個突出的問題。 (請登錄投票,如果你真的需要的功能)

所以,你必須redesgin您的架構來處理這個問題,可能是這樣的

db.test.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}]}) 
db.test.insert({"person" : [ { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]}) 

db.test.find({"person.id":1},{'person.details':1})