将多个文档的数组字段连接成一个数组字段 - MongoDB。

3

我有这个查询:

 [
  {
    '$match': {
      'imageUrls': {
        '$type': 'array', 
        '$ne': []
      }
    }
  }, {
    '$project': {
      'imageUrls': 1, 
      'time': 1
    }
  }, {
    '$sort': {
      'time': 1
    }
  }, {
    '$skip': 0
  }, {
    '$limit': 10
  }
]

这是模式(schema)的定义:
{
    "_id": {
        "$oid": "5ffb0c14dd482daa039ee906"
    },
    "imageUrls": ["image url1", "image url2"],
    "time": 342432432432
}

输出是一个文档列表,每个文档都包含数组字段 imageUrls。 我想把所有 imageUrls 字段中的值放在一个单独的数组字段中。

可能是重复问题 https://dev59.com/c2Ik5IYBdhLWcg3wdd0l - chridam
1个回答

2
  • $sort 按时间降序排序
  • $project 只显示一个字段 imageUrls
  • $unwind 拆分 imageUrls 数组
  • $facet 分离结果,总数和分页文档
  • $skip 跳过文档
  • $limit 文档数量限制
  • $groupnull 分组并重构 imageUrls 数组
  { $sort: { time: -1 } },
  { $project: { imageUrls: 1 } },
  { $unwind: "$imageUrls" },
  {
    $facet: {
      result: [
        { $skip: 0 },
        { $limit: 10 },
        {
          $group: {
            _id: null,
            imageUrls: { $push: "$imageUrls" }
          }
        }
      ],
      count: [
        { $count: "count" }
      ]
    }
  }

Playground


我想按时间对结果进行排序,那么我应该在什么时候使用这些阶段,或者我应该将$sort阶段移到更早的位置? - Rony Tesler
那么跳过和限制应该放在分组之前,对吗? - Rony Tesler
如何获取所有 URL 的总计数,忽略 $skip 和 $limit? - Rony Tesler
1
你应该在 $sort 之前添加 $limit,因为结果文档不能超过16兆字节的 BSON 文档大小限制。 - Haniel Baez
1
@RonyTesler 我已经更新了答案,希望这之后你不再有任何问题。 - turivishal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接