Ayperos23
Ayperos23

Reputation: 19

MongoDB - embedding, inserting one collection into another

If I have a collection (named e.g. people) that looks like

{
   _id: ObjectID("5e12f6260c190f8ee91b162d"),
   name: "Joe Bookreader",
   address: "Highway To Hell 21"
 }

and I want to remove this value for address, and embed the collection (addresses) into it:

               {
                  _id: ObjectID("5e25fg3gjh48ee91b2653"),
                  street: "123 Fake Street",
                  city: "Faketon",
                  state: "MA",
                  zip: "12345"
                }

to look like:

{
   _id: ObjectID("5e12f6260c190f8ee91b162d"),
   name: "Joe Bookreader",
   address: [
                {
                  street: "123 Fake Street",
                  city: "Faketon",
                  state: "MA",
                  zip: "12345"
                }
              ]
 }

How would I do this?

Would it be something similar to inserting the new column, like in the code below (or something completely different)?

 var bulkInsert = db.people.initializeUnorderedBulkOp()
 db.addresses.find().forEach(
    function(doc){
      bulkInsert.insert(doc);
    }
  )

Any help would be appreciated, thanks!

Upvotes: 1

Views: 813

Answers (1)

mickl
mickl

Reputation: 49945

You can run $lookup with empty pipeline to embed one (entire collection) into another.

db.people.aggregate([
    {
        $lookup: {
            from: "addresses",
            pipeline: [ ],
            as: "addresses"
        }
    }
])

Mongo Playground

Then you can either use $out (replace the output collection entirely with aggregation result) or $merge (incorporates aggregation results into existing collection):

EDIT:

You can add $match to target single document instead of entire collection:

db.people.aggregate([
    {
        $lookup: {
            from: "addresses",
            pipeline: [ { $match: { street: "123 Fake Street" } } ],
            as: "addresses"
        }
    }
])

Upvotes: 2

Related Questions