eurojourney
eurojourney

Reputation: 101

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. 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". 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.

Upvotes: 0

Views: 767

Answers (1)

prasad_
prasad_

Reputation: 14287

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; 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:

{ "_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. 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" ] }
  ]
)

Upvotes: 0

Related Questions