[英]How to create an array or embedded document from three existing fields in my collection in MongoDB
First of all, I am new to MongoDB, so this question may be quite simple to answer for some of you.首先,我是 MongoDB 的新手,所以对于你们中的一些人来说,这个问题可能很容易回答。 I am trying to create an array or embedded document that includes existing fields from my collection.我正在尝试创建一个数组或嵌入文档,其中包含我的集合中的现有字段。 In order words, let's say I have a collection with the fields "borough", "street" and "zipcode".换句话说,假设我有一个包含“自治市镇”、“街道”和“邮政编码”字段的集合。 I would like to create an embedded document named, for example, "Location" and move to that document these three fields.我想创建一个名为“位置”的嵌入文档,然后将这三个字段移至该文档。 Is this possible?这可能吗? The following is one of the many different ways I tried to achieve this:以下是我尝试实现这一目标的众多不同方法之一:
db.cooking.aggregate([{$set:{"borough":"$borough", "street":"$street", "zipcode":"$zipcode"}},{$out:"Location"}])
Where I would then use the db.Location.copyTo(cooking) expression to add the data from the newly created aggregate collection "Location" to the main collection "cooking" .然后我将使用db.Location.copyTo(cooking)表达式将数据从新创建的聚合集合 "Location" 添加到主集合"cooking" 。 Of course I would have to remove the existing three fields from the cooking collection since I have the same information in the embedded document Location to avoid having duplicate data.当然,我必须从烹饪集合中删除现有的三个字段,因为我在嵌入的文档Location 中有相同的信息以避免重复数据。
You can create an embedded document with the existing fields, using one of the approaches:您可以使用以下方法之一使用现有字段创建嵌入文档:
Assume you have a collection with the documents like this:假设您有一个包含以下文档的集合:
{ _id: 1, fld1: 12, fld2: "red" },
{ _id: 2, fld1: 9, fld2: "blue" },
{ _id: 3, fld1: 34, fld2: "green" }
and you want to create an embedded document named location
with the fields fld1
and fld2
;并且您想创建一个名为location
的嵌入文档,其中包含字段fld1
和fld2
; the following aggregation will do that:以下聚合将做到这一点:
db.test.aggregate( [
{ $project: { "location.fld1": "$fld1", "location.fld2": "$fld2" } },
{ $out: "test" }
] )
Note that the original collection test
will be overwritten and will be like this:请注意,原始集合test
将被覆盖,如下所示:
{ "_id" : 1, "location" : { "fld1" : 12, "fld2" : "red" } }
{ "_id" : 2, "location" : { "fld1" : 9, "fld2" : "blue" } }
{ "_id" : 3, "location" : { "fld1" : 34, "fld2" : "green" } }
The second approach:第二种方法:
This requires that you are using the MongoDB version 4.2 .这要求您使用 MongoDB 版本4.2 。 This update query just modifies the existing documents in the same collection (with the same result as above):此更新查询仅修改同一集合中的现有文档(结果与上述相同):
db.test.updateMany(
{ },
[
{ $set: { "location.fld1": "$fld1", "location.fld2": "$fld2" } },
{ $unset: [ "fld1", "fld2" ] }
]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.