简体   繁体   English

如何将一个文档保存到 mongodb 中同一数据库的两个不同 collections 中

[英]How to save one document into two different collections of same database in mongodb

I am working on nestjs and I want to fetch one document from collection_1 and save that same document into collection_2.我正在研究nestjs,我想从collection_1 中获取一个文档并将同一个文档保存到collection_2 中。 I used $out aggregation but I only able to save one document in collection 2 at the same time but when I trying to save the second document then the first document has vanished.我使用了 $out 聚合,但我只能同时在集合 2 中保存一个文档,但是当我尝试保存第二个文档时,第一个文档已经消失了。 I want to save every document in collection 2 which is retrieved from the collection 1我想保存从集合 1 中检索到的集合 2 中的每个文档

Service code:服务代码:

async order(name){
    const list=await this.usersmodel.find({name:name}).exec()
    //return list
    try{
        if(list){
            const x=await this.usersmodel.aggregate([
                { $match: { name: name } },
                {$out:"payment"}
            ])
            return "data saved in payment collection"
        }
    }
    catch(error){
        return(error.message)
    }
}

Controller code: Controller 代码:

@Post('orderdata')
async orderdata(@Body('name')name){
    return this.usersService.order(name)
}

If you're on Mongo -v 4.2+ you can use $merge如果您使用的是 Mongo -v 4.2+,则可以使用$merge

await this.usersmodel.aggregate([
    {
        $match: {
            name: name
        }
    },
    {
        $merge: "payment"
    }
])

$merge also has more option to allow you to update existing documents if needed. $merge还具有更多选项,可让您在需要时更新现有文档。

Unfortunately if you're on on older Mongo version this cannot be done in 1 action, you'll have to first query collection1 and then insert to collection2 seperatley.不幸的是,如果您使用的是较旧的 Mongo 版本,这无法在 1 次操作中完成,您必须先查询 collection1,然后插入到 collection2 seperatley。

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

相关问题 同时在数据库 MONGODB 的两个集合中通过电子邮件地址搜索用户 - Searching for a user by email address in two collections in database MONGODB at the same time 如何将文档从一个集合移到另一个集合? Mongoose,MongoDB - How to move document from one collections to another? Mongoose, MongoDB 如何在羽毛应用程序的mongodb中同时使用相同的id删除两个不同集合中的文档 - How to remove document in two different collection using same id at same time in mongodb on feathers application MongoDB:在一个文档中获取所有集合 - MongoDB: Get all collections in one document 如何查询MongoDB中有“一对多”关系的两个collections? - How to query two collections that have a “one-to-many” relationship in MongoDB? 如何使用 MongoDB 或 Mongoose 在一个查询中对两个集合进行分组 - How to group two collections in one query with MongoDB or Mongoose 如何在mongodb中合并两个集合? - How to combine two collections in mongodb? 如何连接两个MongoDb collections? - How to connect two MongoDb collections? 如何在mongodb中合并两个collections,聚合mongodb - How to merge two collections in mongodb, aggregate mongodb 在更新每个文件的文档之前,您可以检查两个不同的 Firestore 集合吗? - Can you check two different firestore collections before updating a document in each one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM