我想将“ displayTitle”更新为“ 12345”,其中objectId为topten =“ 50000以下”的“ title”下的“ 5d8c8f4a4449a851f6kkk6o2”。findOneAndUpdate用于具有两个条件的数组的嵌套对象元素,首先用于选择特定文档,第二个在嵌套数组中查找特定对象。集合名称是:topten。
> db.topten.find().pretty();
{
"_id" : ObjectId("5d8c8f254449a851f6aaa6r3"),
"title" : "under 50000",
"products" : [
{
"_id" : ObjectId("5d8c8f4a4449a851f6kkk6o2"),
"productId" : "5cfe541ae759d9699b5213542",
"displayTitle" : "dhtyks",
"score" : 100,
"priority" : 50,
"description" : "Upcoming"
},
{
"_id" : ObjectId("5d8c8f8f4449a86544646"),
"productId" : "5cfe512bca044365efsdfgg45",
"displayTitle" : "Spice",
"score" : 10,
"priority" : 800,
"description" : "Advanced"
}
],
"created" : ISODate("2019-09-26T10:12:53.804Z"),
"updated" : ISODate("2019-10-03T05:24:19.296Z"),
"slug" : "under-10000",
"__v" : 0
{
"_id" : ObjectId("5d8c8f254449a851f6ddd9a1"),
"title" : "under 10000",
"products" : [
{
"_id" : ObjectId("5d8c8f4a4449a851f6ddd9a2"),
"productId" : "5cfe541ae759d9699b56759b",
"displayTitle" : "ABCDEF6",
"score" : 10,
"priority" : 200,
"description" : "New Gen"
},
{
"_id" : ObjectId("5d8c8f8f4449a851f6ddd9a4"),
"productId" : "5cfe512bca044365ef1dcd0f",
"displayTitle" : "Micromax",
"score" : 1,
"priority" : 200,
"description" : "Upcoming"
}
],
"created" : ISODate("2019-09-26T10:12:53.804Z"),
"updated" : ISODate("2019-10-03T05:24:19.296Z"),
"slug" : "under-10000",
"__v" : 0
我正在使用的代码是:
topten.findOneAndUpdate({"title" : "under 50000", "products": { $elemMatch: { "_id": "5d8c8f4a4449a851f6kkk6o2" } }},
{"products.0.displayTitle":"12345"},
function (err, doc) {
if (err) {
console.log(err);
reject(new Error(err));
return;
} else {
console.log('AAAAAAAAAAAAAAAAAAAAAAAA', doc)
res.status(200)
.json({
success: true,
msg: 'Attached product updated succesfully`);'
})
}
}
)
查询正在运行,但没有更新我的Db中的值。请帮助,我被困在这里。
答案 0 :(得分:0)
尝试在分配产品的地方使用$set。0.displayTitle如下所示:
topten.findOneAndUpdate(
{"title" : "under 50000",
"products": { $elemMatch: { "_id": "5d8c8f4a4449a851f6kkk6o2" } }},
{$set: { products.0.displayTitle: "12345"}},
function (err, doc) {
if (err) {
console.log(err);
reject(new Error(err));
return;
} else {
console.log('AAAAAAAAAAAAAAAAAAAAAAAA', doc)
res.status(200)
.json({
success: true,
msg: 'Attached product updated succesfully`);'
})
}
}
)