【问题标题】:MongoBD $arrayElemAt returning wrong valuesMongoDB $arrayElemAt 返回错误的值
【发布时间】:2021-09-10 17:48:10
【问题描述】:

我的聚合查询中有这个简单的$project 用于返回每个 产品项的第一个图像(字符串)元素并将其存储在first 字段中。

{
    $project: {
      'products._id': 1,
      'products.images': 1,
      'products.first': { $arrayElemAt: ['$products.images', 0] },
    },
  }

但是,当我执行查询时,它会将 first 字段设置为第一个产品的整个图像数组的值。

期望的结果:

{
  "_id": "60d9adda7f017440403d57fb",
  "products": [
    {
      "_id": "5e48a95545f3350017aecce0",
      "images": ["image1","image2"],
      "first": "image1"
    },
    {
      "_id": "5e4c0b0986c1d0001757ae06",
      "images": ["image3"],
      "first": "image3"
    },
    {
      "_id": "5e4c0e1c86c1d0001757ae07",
      "images": ["image4"],
      "first": "image4"
    }
  ]
}

实际结果:

{
  "_id": "60d9adda7f017440403d57fb",
  "products": [
    {
      "_id": "5e48a95545f3350017aecce0",
      "images": ["image1","image2"],
      "first": ["image1", "image2"]
    },
    {
      "_id": "5e4c0b0986c1d0001757ae06",
      "images": ["image3"],
      "first": ["image1", "image2"]
    },
    {
      "_id": "5e4c0e1c86c1d0001757ae07",
      "images": ["image4"],
      "first": ["image1", "image2"]
    }
  ]
}

请问,我该如何解决?

谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    有一些关于它的讨论herehere。这是字段路径表达式的问题,因此您不能那样投影。要获得预期的输出,您可以使用$map:

    db.collection.aggregate([
      {
        $project: {
          products: {
            $map: {
              input: "$products",
              as: "product",
              in: {
                _id: "$$product._id",
                images: "$$product.images",
                first: {
                  "$arrayElemAt": [ "$$product.images", 0 ]
                }
              }
            }
          }
        },
      }
    ])
    

    Mongoplayground

    【讨论】:

    • 此聚合查询仅适用于 MongoDB v4.4 或更高版本。 $first 聚合数组运算符是 v4.4 中引入的一项功能。
    • 我不使用$first 运算符。它只是“first”,一个 op 使用的字段名称。
    • 我看到我的评论是基于假设你可以使用$arrayElemAt 而不是使用$first(这是MongoDB v4.4 的一个特性)。该查询在 $arrayElemAt 的早期版本中运行良好。 我的错!
    猜你喜欢
    • 2021-01-28
    • 2017-04-24
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2015-06-19
    • 2019-02-03
    相关资源
    最近更新 更多