MongoDB聚合 - 如果数组中的值匹配 [英] MongoDB Aggregation - match if value in array

查看:21
本文介绍了MongoDB聚合 - 如果数组中的值匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在执行聚合的集合,我基本上已经把它归结为

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 中计算与值匹配的项目数.之后,一个简单的 $match on mcount >0 将过滤掉不需要的文档.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆