gpt4 book ai didi

mongodb - 如何在 mongodb 中更新子文档

转载 作者:行者123 更新时间:2023-12-05 00:41:32 25 4
gpt4 key购买 nike

我知道这个问题已经被问过很多次了,但我不知道如何在 mongo 中更新子文档。

这是我的架构:

// Schemas
var ContactSchema = new mongoose.Schema({
first: String,
last: String,
mobile: String,
home: String,
office: String,
email: String,
company: String,
description: String,
keywords: []
});

var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
contacts: [ContactSchema]
});

我的收藏是这样的:

db.users.find({}).pretty()
{
"_id" : ObjectId("5500b5b8908520754a8c2420"),
"email" : "test@random.org",
"password" : "$2a$08$iqSTgtW27TLeBSUkqIV1SeyMyXlnbj/qavRWhIKn3O2qfHOybN9uu",
"__v" : 8,
"contacts" : [
{
"first" : "Jessica",
"last" : "Vento",
"_id" : ObjectId("550199b1fe544adf50bc291d"),
"keywords" : [ ]
},
{
"first" : "Tintin",
"last" : "Milou",
"_id" : ObjectId("550199c6fe544adf50bc291e"),
"keywords" : [ ]
}
]
}

假设我想通过以下方式更新 id 为 550199c6fe544adf50bc291e 的子文档:

db.users.update({_id: ObjectId("5500b5b8908520754a8c2420"), "contacts._id": ObjectId("550199c6fe544adf50bc291e")}, myNewDocument)

与 myNewDocument 类似:

{ "_id" : ObjectId("550199b1fe544adf50bc291d"), "first" : "test" }

它返回一个错误:

db.users.update({_id: ObjectId("5500b5b8908520754a8c2420"), "contacts._id":     ObjectId("550199c6fe544adf50bc291e")}, myNewdocument)
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "The _id field cannot be changed from {_id: ObjectId('5500b5b8908520754a8c2420')} to {_id: ObjectId('550199b1fe544adf50bc291d')}."
}
})

我了解 mongo 尝试替换父文档而不是子文档,但最后,我不知道如何更新我的子文档。

最佳答案

您需要使用 $ operator更新数组中的子文档

使用 contacts.$将指向 mongoDB 更新相关的子文档。

db.users.update({_id: ObjectId("5500b5b8908520754a8c2420"), 
"contacts._id": ObjectId("550199c6fe544adf50bc291e")},
{"$set":{"contacts.$":myNewDocument}})

我不确定您为什么要更改_ id的子文档。这是不可取的。

如果您想更改子文档的特定字段,请使用 contacts.$.<field_name>更新子文档的特定字段。

关于mongodb - 如何在 mongodb 中更新子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com