【问题标题】:Select specific fields from a specific element of array by $elemMatch通过 $elemMatch 从数组的特定元素中选择特定字段
【发布时间】:2021-09-16 22:20:50
【问题描述】:

我想从嵌套数组中的特定对象中选择一些特定字段,通过 mongoose/mongo 实现。

Playground Link

考虑数据:

[
  {
    "_id": ObjectId("5ff4b728b6af610f0851d2a6"),
    "totalScore": 500,
    "totalCompleted": 100,
    "monthly": [
      {
        year: 2021,
        month: 8,
        attempted: 10,
        completed: 5,
        score: 20,
        
      }
    ],
    
  },
]

我想首先获取所有文档,然后在“每月”中,我只想选择匹配月份 = 8 的文档,只返回“分数”字段并忽略“尝试”等其他字段"、"完成"等

到目前为止,我已经尝试过以下查询:

db.collection.find({},
{
  totalScore: 1,
  "monthly": {
    $elemMatch: {
      year: 2021,
      month: 8,
      
    },
    
  },
  
})

它返回整个“月”对象的所有键。像这样:

[
  {
    "_id": ObjectId("5ff4b728b6af610f0851d2a6"),
    "monthly": [
      {
        "attempted": 10,
        "completed": 5,
        "month": 8,
        "score": 20,
        "year": 2021
      }
    ],
    "totalScore": 500
  },
]

但是,我想要的是只从“每月”中选择“分数”字段。 所以结果数据是:

[
  {
    "_id": ObjectId("5ff4b728b6af610f0851d2a6"),
    "monthly": [
      {
        "score": 20,
      }
    ],
    "totalScore": 500
  },

我应该如何解决这个问题?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    这可以通过使用$map$filter 的简单聚合来完成:

    db.collection.aggregate([
      {
        $project: {
          totalScore: 1,
          monthly: {
            $map: {
              input: {
                $filter: {
                  input: "$monthly",
                  as: "item",
                  cond: {
                    $eq: [
                      "$$item.month",
                      8
                    ]
                  }
                }
              },
              as: "item",
              in: {
                score: "$$item.score"
              }
            }
          }
        }        
      }      
    ])
    

    mongoplayground 上的示例:https://mongoplayground.net/p/5PbR49Ufxb5

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 2021-08-16
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多