![](/img/trans.png)
[英]MongoDB aggregate function is not returning the value of collection joined using JavaScript
[英]Insert a 2 joined collections to a new collection MongoDB with javascript
我正在嘗試將兩個集合加入一個新集合,同時將結果插入新集合。
我用於加入的代碼:
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"
}
}]))
但是我進入“postsByUsers”集合的結果並不是我所期望的。 我得到了很多額外的字段,例如:_useReadCommands、_cursorid、_batchSize 等。我確實在名為 _batch 的字段中獲得了我需要的信息,但它不像我預期的那樣干凈,我希望它看起來像一個包含對象的數組 +最后的 postsByUser 字段將為我提供所有信息。 當我通過嘗試設置一個等於我所做的連接編碼並循環遍歷它的var
usersPosts 來測試這個時,對於每個文檔: db.postsByUsers.insert(usersPosts)
似乎什么都不做:
usersPosts.forEach(function(doc){
db.postsByUsers.insertOne(doc)
})
我確實設法得到了我想要的結果,但我不知道為什么(奇怪),我嘗試通過我編寫的代碼 go 按下 cmd 上的向上鍵,但似乎沒有什么能給我相同的結果...請幫助並非常感謝您閱讀!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.