arrays - MongoDB:检查对象的数组,如果存在则返回true,否则返回false

标签 arrays mongodb mongodb-query aggregation-framework

我正在尝试查询集合中的数组,如果对象存在于数组中,则投影值“true”。如果对象不存在于数组中,则投影“false”。我在 MongoDB 中工作,我对它不太熟悉。

在我的场景中,我有两个正在使用的集合。我正在汇总一组“员工”成员,并且正在对一组“企业”执行 $lookup 功能。在“业务”中,我拥有一系列业务能力。

例如,我有员工集合

staff = [
  ...
  {_id: 1, businessId: 11},
  {_id: 2, businessId: 22},
  ....
]

企业集合
businesses = [
  ...
  {_id: 11, capabilities: ["claiming", "pushing"]},
  {_id: 22, capabilities: ["claiming", "popping"]},
  ....
]

并有一个 $lookup 设置,如
db.getCollection('staff').aggregate([
    {
        $lookup:
            {
                from: "businesses",
                localField: "businessId",
                foreignField: "_id",
                as: "business_Info"
            }
    },

如果“声称”出现在“能力”中,我如何将每个员工的项目 $project 变成 $canClaim: true 之类的值?

最佳答案

您可以使用 $in 聚合运算符来检查数组是否包含该值。

db.getCollection("staff").aggregate([
  { "$lookup": {
    "from": "businesses",
    "localField": "businessId",
    "foreignField": "_id",
    "as": "business_Info"
  }},
  { "$unwind": "$business_Info" },
  { "$addFields": {
    "canClaim": { "$in": ["claiming", "$business_Info.capabilities"] }
  }}
])

MongoPlayground

关于arrays - MongoDB:检查对象的数组,如果存在则返回true,否则返回false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56072336/

相关文章:

javascript - Nodejs 中的每个模块都需要一个通用的 mongodb 连接

javascript - Mongoose - 从 'pre' 保存 Hook 中的虚拟节点访问数据

node.js - 如何删除列表的内容而不仅仅是列表?如果x在y中,则删除x时也删除y

mongodb - 具有分页数据和总计的 Mongo 聚合

javascript - db.runCommand 意外标记非法

javascript - 如何在数组内的 JavaScript 字符串中添加制表符

c++ - 如何通过引用 C++ 中的函数来传递数组?

python - 无法将数组转换为 float python

java - findAndModify 失败并出现错误 : "Cannot update ' field 1' and ' field1' at the same time

javascript - 从 194481 种可能性中选择随机组合