如何从我的MongoDB集合中的三个现有字段中创建数组或嵌入式文档

问题描述 投票:0回答:1

首先,我是MongoDB的新手,所以对于某些人来说,这个问题可能很简单。我正在尝试创建一个数组或嵌入式文档,其中包括我的收藏中的现有字段。用一个词来说,假设我有一个包含“自治市镇”,“街道”和“邮政编码”字段的集合。我想创建一个嵌入式文档,例如“ Location”,然后将这三个字段移至该文档。这可能吗?以下是我尝试实现此目标的许多不同方法之一:

db.cooking.aggregate([{$set:{"borough":"$borough", "street":"$street", "zipcode":"$zipcode"}},{$out:"Location"}])

然后在哪里使用db.Location.copyTo(cooking)表达式,将新创建的集合“ Location”中的数据添加到主集合“ cooking”。当然,我必须从cooking集合中删除现有的三个字段,因为在嵌入式文档Location中具有相同的信息,以避免重复数据。

arrays mongodb aggregation-framework robo3t embedded-documents
1个回答
0
投票

您可以使用一种方法使用现有字段创建嵌入式文档:

假设您有一个包含如下文档的集合:

{ _id: 1, fld1: 12, fld2: "red" },
{ _id: 2, fld1: 9, fld2: "blue" },
{ _id: 3, fld1: 34, fld2: "green" }

并且您想使用字段locationfld1创建名为fld2的嵌入式文档;以下聚合可以做到这一点:

db.test.aggregate( [
  { $project: { "location.fld1": "$fld1", "location.fld2": "$fld2" } },
  { $out: "test" }
] )

请注意,原始集合test将被覆盖,如下所示:

{ "_id" : 1, "location" : { "fld1" : 12, "fld2" : "red" } }
{ "_id" : 2, "location" : { "fld1" : 9, "fld2" : "blue" } }
{ "_id" : 3, "location" : { "fld1" : 34, "fld2" : "green" } }

第二种方法:

这要求您使用的是MongoDB版本4.2。此更新查询仅修改同一集合中的现有文档(具有与上述相同的结果):

db.test.updateMany(
  { },
  [
      { $set: { "location.fld1": "$fld1", "location.fld2": "$fld2" } },
      { $unset: [ "fld1", "fld2" ] }
  ]
)
© www.soinside.com 2019 - 2024. All rights reserved.