【问题标题】:Update or Insert new data in nested array MongoDB在嵌套数组 MongoDB 中更新或插入新数据
【发布时间】:2020-09-24 08:22:14
【问题描述】:

我将 Node JS 与 Mongoose 一起使用,仅供参考。鉴于我有这样的事情:-

let people = [
    {
        "_id": 1,
        "name": "Person 1",
        "pets": [
            {
                "_id": 1,
                "name": "Tom",
                "category": "cat",
                "favFood": [
                    {
                        "_id": 1,
                        "name": "steamed fish"
                    }
                ]
            },
            {
                "_id": 2,
                "name": "Jerry",
                "category": "mouse",
                "favFood": [
                    {
                        "_id": 1,
                        "name": "cheese"
                    }
                ] 
            }
        ]
    }
]

现在我知道如何insert new pet 数据如下所示:-

// new Pet Data to INSERT
let newPetData = {
    name: "Butch",
    category: "dog",
    favFood: [
        {
            name: "bone"
        }
    ]    
}

// INSERT new data in DB
People.updateOne(
    // push into the sub-documents - pets
    { $push: { pets: newPetData } },
    (err, success) => {
        if(err) res.json({ message: `Unsuccessful!`, report: err })
        else res.json({ message: `Successful!`, report: success })
    }
)

但是,如果我有 id (宠物的 ID),我如何插入 pet 的新 favFood 数据?

let petID = 1 // this is the ID of pet named Tom

// this is a new favorite food of Tom to INSERT
let newFavFood = {
    name: "fried fish"
}

// code to INSERT new favorite food of Tom (THIS DOES NOT WORK!)
People.updateOne(
    { "_id": petID } // id of pet 'Tom'
    { $push: { favFood: newFavFood } }, // push into the sub-documents - favFood
    (err, success) => {
        if(err) res.json({ message: `Unsuccessful!`, report: err })
        else res.json({ message: `Successful!`, report: success })
    }
)    

上面的代码不起作用。我认为如果我指定{ "_id": petID } 上方的宠物的id 会产生我想要的。即使它返回 messageSuccessful!。但是 没有向 db 本身添加新记录。我正在寻找的结果将是如下所示:-

let people = [
    {
        "_id": 1,
        "name": "Person 1",
        "pets": [
            {
                "_id": 1,
                "name": "Tom",
                "category": "cat",
                "favFood": [
                    {
                        "_id": 1,
                        "name": "steamed fish"
                    },
                    {
                        "_id": 2, 
                        "name": "fried fish" // this is the new data inserted
                    }
                ]
            },
            {
                "_id": 2,
                "name": "Jerry",
                "category": "mouse",
                "favFood": [
                    {
                        "_id": 1,
                        "name": "cheese"
                    }
                ] 
            }
        ]
    }
]

有没有其他方法可以做到这一点?我必须在此实施$elemMatch 吗?如果是这样,我该怎么做?

【问题讨论】:

    标签: arrays mongodb nested mongodb-query insert-update


    【解决方案1】:

    查询部分匹配文档,而不是元素,所以{ "_id": petID } 匹配人的_id。要匹配宠物,请使用{ "pets._id": petID }等点符号

    然后使用位置运算符$ 引用第一个匹配查询部分的数组元素:

    .updateOne(
        { "pets._id": petID },
        { $push: { "pets.$.favFood": newFavFood }}
    )
    

    【讨论】:

    • “使用位置运算符$ 引用与查询部分匹配的第一个数组元素”是什么意思?
    • 在示例中,查询部分{ "pets._id": petID } 匹配pets 数组元素的_id 字段。在更新部分中,pets.$ 指的是pets 数组中满足查询部分的第一个元素。见docs.mongodb.com/manual/reference/operator/update/positional/…
    • 它在您刚刚给我的文档中说过,如果我要在favFood 数组之后再添加一个嵌套数组,例如:favFood [{ _id: 1, name: Fried fish, Nutrition: [{ _id: 1, name: Vit A }, { _id: 1, name: Vit B }] }]。我在favFood 数组中添加了 名为Nutrition 的新数组。所以如果我想push new data to Nutrition 数组我不能使用这个方法?对于这种操作,您有任何我可以参考的文档吗?
    • 在这种情况下,您需要使用array filters,并为每个数组指定一个过滤器
    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    相关资源
    最近更新 更多