2015-04-02 116 views
1

我有一個MongoDB集合具有以下對象結構計算,MongoDB的findby一列,並通過其他

{ 
    name: "hotel", 
    products: [ 
     { 
      id: 1, 
      name: "flower" 
     }, 
     { 
      id: 350, 
      name: "chocolate" 
     } 
    ] 
} 

需要找到的所有對象:

一)具有名稱「酒店」和

二)產品數量是大於4 count($products)

我嘗試沒有成功如下:

db.foo.find($and: [{name: "hotel"}, {products: {$gt: 4}}]); 

回答

4

爲了找到所需的產品陣列中元件的數量,使用的dot notation$exists的組合來尋找數組索引4(因爲在JavaScript數組索引是從0開始)。如果該索引存在,那麼就意味着你的文件有大小大於或等於5的陣列你最終的查詢應該像

var query = { "name": "hotel", "products.4": { "$exists": true } }; 
db.foo.find(query); 

另一種選擇是使用$where操作:

var query = { "name": "hotel", "products" : { "$exists": true }, "$where": "this.products.length > 4"}) 
db.foo.find(query); 

兩個

db.foo.insert([ 
{ 
    name: "hotel", 
    products: [ 
     { 
      id: 1, 
      name: "flower" 
     }, 
     { 
      id: 350, 
      name: "chocolate" 
     } 
    ] 
}, 
{ 
    name: "hotel", 
    products: [ 
     { 
      id: 1, 
      name: "flower" 
     }, 
     { 
      id: 350, 
      name: "chocolate" 
     }, 
     { 
      id: 380, 
      name: "candy" 
     }, 
     { 
      id: 390, 
      name: "milk" 
     }, 
     { 
      id: 3, 
      name: "newspaper" 
     }, 
    ] 
} 
]) 

上述返回的查詢文檔:

與該樣本數據測試查詢
{ 
    "_id" : ObjectId("551d6706180e849972938f8e"), 
    "name" : "hotel", 
    "products" : [ 
     { 
      "id" : 1, 
      "name" : "flower" 
     }, 
     { 
      "id" : 350, 
      "name" : "chocolate" 
     }, 
     { 
      "id" : 380, 
      "name" : "candy" 
     }, 
     { 
      "id" : 390, 
      "name" : "milk" 
     }, 
     { 
      "id" : 3, 
      "name" : "newspaper" 
     } 
    ] 
} 
+0

是在文檔中找到'$ size'運算符,但問題是,在它不需要像'$ gt'這樣的其他運算符後 – 2015-04-02 15:38:51

+0

更改查詢以使用點運算符來檢查數組是否存在長度 – chridam 2015-04-02 15:40:09

+0

我試過了你的查詢,但也沒有成功:( – 2015-04-02 15:46:20