嵌入式阵列更新后如何取回新值

嵌入式阵列更新后如何取回新值

本文介绍了嵌入式阵列更新后如何取回新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

给出以下MongoDB集合:

Given the following MongoDB collection:

{
    "_id": ObjectId("56d6a7292c06e85687f44541"),
    "name": "My ranking list",
    "rankings": [
        {
            "_id": ObjectId("46d6a7292c06e85687f55542"),
            "name": "Ranking 1",
            "score": 1
        },
        {
            "_id": ObjectId("46d6a7292c06e85687f55543"),
            "name": "Ranking 2",
            "score": 10
        },
        {
            "_id": ObjectId("46d6a7292c06e85687f55544"),
            "name": "Ranking 3",
            "score": 15
        },
    ]
}

这是我如何提高给定排名的分数:

Here is how I increase the score of a given ranking:

db.collection.update(
    { "_id": ObjectId("56d6a7292c06e85687f44541"), "rankings._id" : ObjectId("46d6a7292c06e85687f55543") },
    { $inc : { "rankings.$.score" : 1 } }
);

如何获取新的分数值?在上一个查询中,我将第二个排名从10增加到11 ...更新后如何重新获得这个新值?

How do I get the new score value? In the previous query I increase the second ranking from 10 to 11... How do I get this new value back after the update?

推荐答案

如果您使用的是MongoDB 3.0或更高版本,则需要使用 .findOneAndUpdate() 并使用projection选项指定要返回的字段子集.您还需要将returnNewDocument设置为true.当然,您需要在此处使用 $elemMatch 投影运算符,因为您不能使用位置投影并返回新文档.

If you are on MongoDB 3.0 or newer, you need to use the .findOneAndUpdate() and use projection option to specify the subset of fields to return. You also need to set returnNewDocument to true. Of course you need to use the $elemMatch projection operator here because you cannot use a positional projection and return the new document.

有人指出:

db.collection.findOneAndUpdate(
    {
        "_id": ObjectId("56d6a7292c06e85687f44541"),
         "rankings._id" : ObjectId("46d6a7292c06e85687f55543")
    },
    { $inc : { "rankings.$.score" : 1 } },
    {
        "projection": {
            "rankings": {
                "$elemMatch": { "_id" : ObjectId("46d6a7292c06e85687f55543") }
            }
        },
        "returnNewDocument": true
    }
)

从MongoDB 3.0开始,您需要使用 findAndModify fields选项,还需要将new设置为true,以返回新值.

From MongoDB 3.0 onwards, you need to use findAndModify and the fields options also you need to set new to true in other to return the new value.

db.collection.findAndModify({
    query: {
        "_id": ObjectId("56d6a7292c06e85687f44541"),
        "rankings._id" : ObjectId("46d6a7292c06e85687f55543")
    },
    update: { $inc : { "rankings.$.score" : 1 } },
    new: true,
    fields: {
        "rankings": {
            "$elemMatch": { "_id" : ObjectId("46d6a7292c06e85687f55543") }
        }
    }
})

两个查询都产生:

{
        "_id" : ObjectId("56d6a7292c06e85687f44541"),
        "rankings" : [
                {
                        "_id" : ObjectId("46d6a7292c06e85687f55543"),
                        "name" : "Ranking 2",
                        "score" : 11
                }
        ]
}

这篇关于嵌入式阵列更新后如何取回新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:11