【问题标题】:How to Project an Element in an Array of Objects in mongoDB for All Documents from a Collection如何在 mongoDB 中为集合中的所有文档投影对象数组中的元素
【发布时间】:2022-11-30 17:39:00
【问题描述】:

我的公司集合中有一组对象,其中包含如下分组值:

"groups" : [
        {
            "id" : "d278c44333",
            "name" : "group 1"
        }
    ],

所以在 mongoDB 中它将是company > groups > 0 > id or name

我想投影所有具有对象组数组的文档并检索名称。

我怎样才能做到这一点?

这是我尝试过的:

db.getCollection("Company").aggregate([
            
    {
        $match: { 
            "companyID": "323452343",

        }
    },

    {
        $project: { 
            //this only projects groupName with an array with 0 elements inside.
            groupName: "$groups.0.name"

         }
        
    }

])

【问题讨论】:

  • 是否要获取所有包含“$groups.0.name”的文档而不考虑其值?
  • @nimrodserok 是的,但是它总是有一个值,因为在我的集合中,每个文档都有这个 groups 对象数组,带有 id 和 name

标签: mongodb mongodb-query


【解决方案1】:

对于第一项使用的具体情况:

db.collection.aggregate([
  {
    $match: {
      groups: {
        $elemMatch: {
          id: "d278c44333"
        }
      }
    }
  },
  {
    $project: {
      groupName: {
        $first: "$groups.name"
      }
    }
  }
])

查看它在playground example 上的工作原理

对于其他情况,请使用$arrayElemAt

【讨论】:

  • 但我希望所有组元素名称不仅仅是一个元素名称,我将如何实现?问题中的案例只是一个例子。
  • 请提供数组中包含少量项目的有效文档及其预期结果,我会更新答案
猜你喜欢
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多