我正在try 创建一个调用,该调用将‘图像’和‘posts.Image’之间的所有图像组合在一起,并按createdAt排序.到目前为止,我有:

output = [Array(1), Array(3), {…}, {…}, {…}, {…}, {…}, {…}]

因此,它似乎是将这些数组合并到一个父数组中,而不是合并到一个单独的数组中.

我想要的是:

output = [{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…}]

以下是我的方案:

const deviceSchema = new Schema({
owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
},
images: [{
    url: {
        type: String,
    },
    createdAt: {
        type: Date,
    }
}],
posts: [{
    description: {
        type: String,
    },
    images: [{
        url: {
            type: String,
        },
        createdAt: {
            type: Date,
        }
    }],
    createdAt: {
        type: Date,
    }
}],
});

以下是我的综合预测:

const images = await Device.aggregate([
        { $project: {
            combinedImages: { $concatArrays: ["$images", "$posts.images"] }
        }},
        { $match: { _id: id }},
        { $unwind: '$combinedImages' },
        { $sort: { 'combinedImages.createdAt': -1 }},
        { $skip: (page-1)*limit },
        { $limit: limit },
        { $group: { _id: '$_id', images: { $push: '$combinedImages'}}}
    ])

推荐答案

您可以使用$concatArrays$reduce的组合将所有图像合并到单个数组中,例如:

db.collection.aggregate([
  {
    $set: {
      combinedImages: {
        "$concatArrays": [
          "$images",
          {
            $reduce: {
              input: "$posts",
              initialValue: [],
              in: {
                "$concatArrays": [
                  "$$value",
                  "$$this.images"
                ]
              }
            }
          }
        ]
      }
    }
  }
])

这将导致以下输出:

{
    // ...
    "combinedImages": [
      {
        "url": "img1"
      },
      {
        "url": "img2"
      },
      {
        "url": "post_img11"
      },
      {
        "url": "post_img12"
      },
      {
        "url": "post_img21"
      },
      {
        "url": "post_img22"
      }
    ],
    // ...
}

看看这个mongoplayground来测试一下.

Mongodb相关问答推荐

使用查询参数过滤MongoDB Go驱动程序时出现问题

会话的Mongo-go驱动程序版本.Copy()

MongoDB-如何过滤和获取数组字段中的最新数据

如何填充Mongoose中的嵌套引用

Mongoose 查询以获取内部数组和该内部数组中的特定元素

Mongo聚合的具体格式

Mongoose 更新不同类型的记录

MongoDB C# 驱动程序 2.0 InsertManyAsync 与 BulkWriteAsync

如何将记录从一个 mongo 数据库插入另一个?

无法使用机器 ip 连接到 mongodb

嵌套在文档数组中的mongodb展开数组

Spring Mongodb @DBREF

将 MongoDB 数据库复制到本地计算机

MongoDB + Node JS + 基于角色的访问控制 (RBAC)

mongodb启动错误

docker 在不同的端口上运行 mongo 映像

了解 Mongoose 中的关系和外键

无法连接到远程服务器上的 mongo

多次使用位置 `$` 运算符来更新嵌套数组

如何在 Ubuntu 10.04 中使用 --auth 选项重新启动 mongodb?