MongoDb的$(更新)不更新数组的元素,而是替换它?

时间:2021-09-19 02:35:45

I want to update an element of an array inside mongodb's document (I am using mongoose). Schema is something like:

我想更新mongodb文档中的数组元素(我使用的是mongoose)。架构是这样的:

{
 ..
 arr : [{
  foo: Number,
  bar: [String],
  name: String
 }]
 ..
}

And my query is:

我的疑问是:

SomeModel.update({
 _id: "id of the document",
 arr: {
  $elemMatch: {
   _id: "_id assigned by mongoose to array element"
  }
 }
}, {
 'arr.$': {
  name: 'new name'  
 }
}).exec()

It just replaces whole array element say:

它只是替换整个数组元素说:

{
 _id: "some objectId",
 name: 'old name',
 foo: 0,
}

to:

{
 name: 'new name'
}

what I want:

我想要的是:

{
 _id: "some objectId",
 name: 'new name',
 foo: 0,
}

What I am curious to know if it is possible to achieve this in single update query ? (May be there is a silly mistake in my query :P or another approach)

我很想知道是否有可能在单个更新查询中实现这一点? (可能是我的查询中存在一个愚蠢的错误:P或其他方法)

I would also like to do update query like so:

我也想像这样做更新查询:

{
 $inc: { foo: 1},
 $push: { bar: "abc"}
}

1 个解决方案

#1


1  

If you are still struggling with the whole implementation the full application of your statement is as follows:

如果您仍在努力完成整个实施,您的声明的完整应用如下:

SomeModel.update(
    {
        "arr._id": "123"
    },
    {
        "$set": { "arr.$.name": "new name" },
        "$inc": { "arr.$.foo": 1},
        "$push": { "arr.$.bar": "abc" }
    }
)
,function(err,numAffected) {

});

So each operation is performed in turn.

因此,每个操作依次执行。

#1


1  

If you are still struggling with the whole implementation the full application of your statement is as follows:

如果您仍在努力完成整个实施,您的声明的完整应用如下:

SomeModel.update(
    {
        "arr._id": "123"
    },
    {
        "$set": { "arr.$.name": "new name" },
        "$inc": { "arr.$.foo": 1},
        "$push": { "arr.$.bar": "abc" }
    }
)
,function(err,numAffected) {

});

So each operation is performed in turn.

因此,每个操作依次执行。