在 mongodb 中过滤数组 [英] Filter arrays in mongodb

查看:27
本文介绍了在 mongodb 中过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,其中每个文档包含 2 个文档数组,如下所示.

I have a collection where each document contains 2 arrays of documents as below.

{
  all_users:[
    {
      id:1,
      name:"A"
    },
    {
      id:2,
      name:"B"
    },
    {
      id:3,
      name:"C"
    }
  ]
  selected_users:[
    {
     id:1,
      name:"A"
    },
    {
      id:2,
      name:"B"
    }
  ]
}

是否可以通过添加字段 selected 并根据用户名称是否存在于 selected_users 中的文档中为其分配值来合并 2 个数组代码>数组如下.

Is it possible to merge the 2 arrays by adding a field selected and assigning a value to it based on whether the name of the user is present in a document in the selected_users array as follows.

{
  all_users:[
    {
      id:1,
      name:"A",
      selected:"yes"
    },
    {
      id:2,
      name:"B",
      selected:"yes"
    },
    {
      id:3,
      name:"C",
      selected:"no"
    }
  ]
}

我想通过 idname 进行检查,因为文档可能包含其他字段.我不知道如何实现这一点.

I want to check by id or name since the documents may contain additional fields. I can't figure out how to achieve this.

推荐答案

  • $map 迭代 all_users 数组的循环
  • $cond 检查条件,如果 id 在选定用户 id 中,则返回yes";否则否"在 selected 字段
  • $mergeObject 将当前用户对象与上面的 selected 字段合并
    • $map to iterate loop of all_users array
    • $cond check condition if id is in selected users id then return "yes" otherwise "no" in selected field
    • $mergeObject to merge current user object with above selected field
    • db.collection.aggregate([
        {
          $project: {
            all_users: {
              $map: {
                input: "$all_users",
                in: {
                  $mergeObjects: [
                    "$$this",
                    {
                      selected: {
                        $cond: [
                          { $in: ["$$this.id", "$selected_users.id"] },
                          "yes",
                          "no"
                        ]
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      ])
      

      游乐场

      这篇关于在 mongodb 中过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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