简体   繁体   English

如何在mongodb中的.aggregation之后插入一个数组作为新文档?

[英]How to insert an array as a new document after the .aggregation in mongodb?

I wanner insert a var object as a new document after aggregation operation in MongoDB.我想在 MongoDB 中的聚合操作后插入一个 var object 作为新文档。 I try this method:我试试这个方法:

    var postUpvote = db.collection.aggregation([
    {$limit:1}
    ]).toArray()

    db.collection.aggregation([
    ...
    ...
    ]).insert(postUpvote[0])

But db.collection.aggregation(...).instert() is not a function.但是 db.collection.aggregation(...).instert() 不是 function。 The second aggregation result is just one document.第二个聚合结果只是一个文档。 And I also try to use $addFields to insert the postUpvote to the document, but I can't take this inserted file out of the document into a new document.而且我还尝试使用 $addFields 将 postUpvote 插入到文档中,但是我无法将此插入的文件从文档中取出到新文档中。

{
    "_id" : 1671,
    "CommentUserId" : 1671,
    "CommentUserUpVote" : 2644,
    "PostUserId" : 1671,
    "PostUserVote" : 2644
}

The PostUserId and PostUserVote is the var postUpvote. PostUserId 和 PostUserVote 是 var postUpvote。 The result I want is我想要的结果是

{
    "_id" : 1671,
    "CommentUserId" : 1671,
    "CommentUserUpVote" : 2644,
}
{
    "_id": //Whatever, I don't care
    "PostUserId" : 1671,
    "PostUserVote" : 2644
}

You can use $out aggregation as a last step in your pipeline.您可以使用$out聚合作为管道中的最后一步。 But it replaces the output collection completely if it already exists.但如果 output 集合已经存在,它将完全替换它。 If you want to avoid it try $merge aggregation.如果你想避免它尝试$merge聚合。 It can incorporate results (insert new documents, merge documents, replace documents, keep existing documents, fail the operation, process documents with a custom update pipeline) into an existing collection.它可以将结果(插入新文档、合并文档、替换文档、保留现有文档、操作失败、使用自定义更新管道处理文档)合并到现有集合中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM