Hadar Yamin
Hadar Yamin

Reputation: 1

Insert a 2 joined collections to a new collection MongoDB with javascript

I'm trying to join two collection to a new collection while inserting the result to the new collection.

The code I use for join:

db.users.aggregate(
  [{
    $lookup: {
      from: "posts",
      localField: "_id",
      foreignField: "_uid",
      as: "postsByUser"
    }
  }])

I know that this returns a new collection/array Now,I can insert this new array into a new collection like this:

db.postsByUsers.insert(db.users.aggregate(
  [{
    $lookup: {
      from: "posts",
      localField: "_id",
      foreignField: "_uid",
      as: "postsByUser"
    }
  }]))

But the result it that im getting in the collection "postsByUsers" isn't what I was expecting. I get alot of additional field like: _useReadCommands,_cursorid,_batchSize etc. I do get the information I need in the field called _batch but its not as clean as I expected, I want it to look like an array with objects inside of it + the postsByUser field at the end that will give me all the Information. As im testing this with trying to set a var usersPosts that equal to the join coding I did and looping through it and For each doc: db.postsByUsers.insert(usersPosts) that seems to do nothing:

usersPosts.forEach(function(doc){
  db.postsByUsers.insertOne(doc)
})

The weird thing that I did manage to get the result I wanted but I don't know why(weird), I tried to go through the code I wrote With pressing the up key on the cmd bvut nothing seems to give me the same result...Please help and thank you so much for Reading!

Upvotes: 0

Views: 148

Answers (1)

thammada.ts
thammada.ts

Reputation: 5245

You can use $out aggregation pipeline stage to output the result of an aggregation pipeline into another collection

{ $out: 'postsByUsers' }

From MongoDB 4.2 onwards you can also use $merge, which is more flexible and can merge the result documents with existing ones.

Upvotes: 1

Related Questions