使用JavaScript将2个已加入的集合插入到新集合MongoDB中

我正在尝试将两个集合添加到新集合中,同时将结果插入到新集合中。

我用于加入的代码:

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

我知道这将返回一个新的集合/数组 现在,我可以将这个新数组插入到这样的新集合中:

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)
})

我确实设法获得了想要的结果,但是我不知道为什么(很奇怪),这是很奇怪的事情,我试图遍历我编写的代码。在cmd bvut上按下up键似乎没有给我相同的结果...请帮助并非常感谢您的阅读!

评论
仰起头~
仰起头~

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.

点赞
评论