簡體   English   中英

如何將嵌套屬性保存在 MongoDB 的新集合中的新文檔中?

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

我是 MongoDB 的新手,仍在嘗試了解更多信息。 我正在嘗試通過從另一個集合復制嵌套屬性來在一個集合中創建一個新文檔。 例如:

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

    }
]

我正在嘗試將嵌套的“productid”及其相應數量保存到新集合中的新文檔中。

您可以簡單地從一個集合中獲取數據並將其存儲到一個數組中並轉儲到另一個集合中。 如果需要,您還可以對該數組執行一些操作。 這是工作示例....

 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