2015-04-02 118 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