首页 > 解决方案 > 转换 mongo 数组

问题描述

我有一个集合,其中包含像

{
   "_id": ObjectId("60f561eb0d022a4c614966c1"),
   "vehicleId": 288,
   "startTime": [
      ISODate("2021-06-19T13:00:19Z"),
      ISODate("2021-06-19T13:00:40Z")
   ],
   "odo": [0, 1116.0746443123298],
   "location": [
      { "type": "Point", "coordinates": [75.759973, 26.977889] },
      { "type": "Point", "coordinates": [75.771209, 26.97858] }
   ]
}

我想更改位置数组,使文档看起来像

{
   "_id": ObjectId("60f561eb0d022a4c614966c1"),
   "vehicleId": 288,
   "startTime": [
      ISODate("2021-06-19T13:00:19Z"),
      ISODate("2021-06-19T13:00:40Z")
   ],
   "odo": [0, 1116.0746443123298],
   "locations": [
      { loc: { "type": "Point", "coordinates": [75.759973, 26.977889] } },
      { loc: { "type": "Point", "coordinates": [75.771209, 26.97858] } }
   ]
}

也就是说,每个条目都成为一个对象。我可能想对 odo 和 starttime 做同样的事情。

我正在尝试聚合管道,但除了使用应用程序代码来读取和转换对象之外,我还没有找到其他方法。

我宁愿通过仅 mongo 的方式来做,而不是使用应用程序并逐个文档解析文档,因此非常感谢任何有关 mongo-only 方式的帮助。

标签: arraysmongodbaggregation-framework

解决方案


会是这个:

db.collection.aggregate([
  {
    $set: {
      location: "$$REMOVE",
      locations: {
        $map: {
          input: "$location",
          in: { loc: "$$this" }
        }
      }
    }
  }
])

推荐阅读