i have documents this
{ "_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 ] }
and want find document array 'prices' containing highest amount of digit 4, in case third document. there way query it?
starting mongodb 3.2, can $project
our documents , use $size
, $filter
operator return "count" of number 4
in each array. there need $group
using "value" , use $push
accumulator operator return array of documents have same "maximum". next $sort
documents _id
, use $limit
return documents maximum occurrence of 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 } ] )