MongoDB聚合-如果数组中的值匹配 [英] MongoDB Aggregation - match if value in array
问题描述
我有一个要对其进行汇总的集合,基本上已经将其归结为
I have a collection that I'm performing an aggregation on and I've basically gotten it down to
{array:[1,2,3], value: 1},
{array:[1,2,3], value: 4}
我将如何执行聚合匹配以检查该值是否在数组中?我尝试使用{$match: {"array: {$in: ["$value"]}}}
,但找不到任何东西.
How would I perform an aggregation match to check if the value is in the array? I tried using {$match: {"array: {$in: ["$value"]}}}
but it doesn't find anything.
我希望输出(如果以上面的示例为例)为
I would want the output (if using the above as an example) to be:
{array:[1,2,3], value:1}
推荐答案
基于@chridam的回答略有不同:
A slight variation based on @chridam's answer:
db.test.aggregate([
{ "$unwind": "$array" },
{ "$group": {
_id: { "_id": "$_id", "value": "$value" },
array: { $push: "$array" },
mcount: { $sum: {$cond: [{$eq: ["$value","$array"]},1,0]}}
}
},
{ $match: {mcount: {$gt: 0}}},
{ "$project": { "value": "$_id.value", "array": 1, "_id": 0 }}
])
想法是$unwind
和$group
返回数组,并在mcount
中计算与该值匹配的项目数.之后,在mcount > 0
上使用简单的$match
即可过滤掉不需要的文档.
The idea is to $unwind
and $group
back the array, counting in mcount
the number of items matching the value. After that, a simple $match
on mcount > 0
will filter out unwanted documents.
这篇关于MongoDB聚合-如果数组中的值匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!