如何在mongoDB中更新数组内部

时间:2018-12-18 13:07:06

标签: mongodb

在这里,我想像在标签数组内部那样编写更新查询,假设值是good,我想更改very-good。我已经写了,但是工作不正常,假设插入tags两个值就是手段,两个值本身就会更新

  

我的文档

    /* 1 createdAt:12/18/2018, 5:59:33 PM*/
{
    "_id" : ObjectId("5c18e82da073cdc5c70072dc"),
    "roleID" : "3",
    "tags" : [
        "good"
    ]
},

/* 2 createdAt:12/18/2018, 5:59:33 PM*/
{
    "_id" : ObjectId("5c18e82da073cdc5c70072db"),
    "roleID" : "2",
    "tags" : [
        "very-good",
        "good"
    ]
},

3 个答案:

答案 0 :(得分:1)

此代码运行良好,它使用updateMany而不是update。这段代码使用 $运算符

代码

db.QuestionContents.updateMany({contentID: {$in: contentID}, tags: "options-short"}, {$set: {"tags.$": "options-2x2"}});

docs

中的更多信息

输出

这是db.QuestionContents.find({})的结果:

Output

答案 1 :(得分:0)

使用此查询进行更新-

db.QuestionContents.update({contentID: {$in: contentID}, tags: "options-short" }, {$set:{"tags.$":"options-short2*2"}},{"multi": true});

答案 2 :(得分:0)

$addToSet$each一起使用

db.QuestionContents.update({contentID: {$in: contentID} }, {$addToSet:{tags:{
  $each:["options-2x2"]}}},{"multi": true});