简体   繁体   English

如何将嵌套属性保存在 MongoDB 的新集合中的新文档中?

[英]How to get nested properties to be saved in a new document in a new collection in MongoDB?

I am new to MongoDB and still trying to learn more.我是 MongoDB 的新手,仍在尝试了解更多信息。 I am trying to create a new document in one collection by copying nested properties from another collection.我正在尝试通过从另一个集合复制嵌套属性来在一个集合中创建一个新文档。 For example:例如:

userId: 12345
products: [
    {
        "productId": "123",
        "quantity": 1
    },
    {
        "productId": "124",
        "quantity": 2,

    }
]

I am trying to get the nested "productid" with their corresponding quantity to be saved to a new document in a new collection.我正在尝试将嵌套的“productid”及其相应数量保存到新集合中的新文档中。

You can simply get data from one collection and store into an array and dump into another.您可以简单地从一个集合中获取数据并将其存储到一个数组中并转储到另一个集合中。 You can also perform some operations on that array if you want.如果需要,您还可以对该数组执行一些操作。 Here is working example....这是工作示例....

 const dataFromOneCollection = [ { userId: 12345, products: [ { productId: "123", quantity: 1, }, { productId: "124", quantity: 2, }, ], }, { userId: 6789, products: [ { productId: "456", quantity: 1, }, { productId: "245", quantity: 2, }, ], }, ]; // map data and flat it to one array const dataToStoreAnotherCollection = dataFromOneCollection.map(i => i.products).flat(1); console.log(dataToStoreAnotherCollection); // insert data to another collection db.collection("products").insertMany(dataToStoreAnotherCollection);

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

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