2016-06-06 38 views
2

我喜欢这个查找文件包含一个特定的值

{ "_id" : ObjectId("5755d81e2935fe65f5d167aa"), "prices" : [ 23, 11, 2, 3, 4, 1, 232 ] }, 
{ "_id" : ObjectId("5755d81e2935fe65f5d167ab"), "prices" : [ 99, 3, 23, 23, 12 ] }, 
{ "_id" : ObjectId("5755d81e2935fe65f5d167ac"), "prices" : [ 999, 12, 3, 4, 4, 4, 4, 4, 123 ] }, 
{ "_id" : ObjectId("5755d81e2935fe65f5d167ad"), "prices" : [ 24, 3, 4, 5, 6, 7, 723 ] } 

文档的最大occurence阵列,我想找到阵“价格”含有在数字4的最高金额,文件我的情况是第三个文件。有什么方法可以查询它吗?

+0

使用此答案为例如:http://stackoverflow.com/questions/20850824/how-to-count-occurrences-in-nested-document-in-mongodb –

+0

这一个,以及:HTTP:/ /stackoverflow.com/questions/14319616/how-to-count-occurence-of-each-value-in-array –

+0

类似于'db.prices.aggregate([{$ unwind:“$ prices”},{$ sort :{“prices”:-1}},{$ limit:1}])''可以帮助 –

回答

2

从MongoDB的3.2开始,我们可以$project我们的文件,并使用$size$filter运营商每个数组中返回数4的“计数”。从那里我们需要$group使用该“值”,并使用累加器运算符来返回具有相同“最大值”的文档数组。接下来你你的文件由_id和使用$limit返回文档的最大出现4

db.collection.aggregate(
    [ 
     { "$project": { 
      "prices": 1, 
      "counter": { 
       "$size": { 
        "$filter": { 
         "input": "$prices", 
         "as": "p", 
         "cond": { "$eq": [ "$$p", 4 ] } 
        } 
       } 
      } 
     }}, 
     { "$group": { 
      "_id": "$counter", 
      "docs": { "$push": "$$ROOT" } 
     }}, 
     { "$sort": { "_id": -1 } }, 
     { "$limit": 1 } 
    ] 
) 
相关问题