推送后获取索引

发布于 2024-12-20 01:37:46 字数 220 浏览 2 评论 0原文

使用 $push 修饰符将新值推入数组后如何获取新索引?

例如,我在文档中有一个数组,

{ ...
    'myarray': [1, 2, 3]
 ....
}

myarray中推送后说数字10,希望获得索引号3。

我正在考虑使用count方法,但认为它不会是原子的。

How do I get new index after use $push modifier to push a new value into an array?

For example, I have an array in a doc,

{ ...
    'myarray': [1, 2, 3]
 ....
}

After push say number 10 in myarray, wish to get index number 3.

I am thinking use count method, but think it wouldn't be atomic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瘫痪情歌 2024-12-27 01:37:46

它不会是原子的。执行此类操作的最佳方法是使用 findAndModify:

http://www.mongodb。 org/display/DOCS/findAndModify+Command

这是一个自动应用 $push 更新并返回结果文档的示例。请注意,findAndModify 调用返回应用了推送的“新”文档。这是原子的。

MongoDB shell version: 2.1.0
connecting to: test
> db.z.save({"a":[], "name": "list1"})
> db.runCommand({ "findAndModify": "z", "query": { "name": "list1" }, "update": { "$push": { "a": 64 } }, "new": true })
{
        "lastErrorObject" : {
                "updatedExisting" : true,
                "n" : 1,
                "connectionId" : 65,
                "err" : null,
                "ok" : 1
        },
        "value" : {
                "_id" : ObjectId("4ee27202c469f4b2d3c6cbf9"),
                "a" : [ 
                        64
                ],
                "name" : "list1"
        },
        "ok" : 1
}
> db.z.find()
{ "_id" : ObjectId("4ee27202c469f4b2d3c6cbf9"), "a" : [ 64 ], "name" : "list1" }

然后,您将在客户端代码中计算索引。请注意,后续操作可能会导致该索引无效(即后续的删除、$set 或 $pull)——处理这种情况取决于您的应用程序。

It would not be atomic. The best way to do something like this is to use findAndModify:

http://www.mongodb.org/display/DOCS/findAndModify+Command

Here's an example that would atomically apply the $push update and return the resulting document. Note that the findAndModify call returns the "new" document with the push applied. This is atomic.

MongoDB shell version: 2.1.0
connecting to: test
> db.z.save({"a":[], "name": "list1"})
> db.runCommand({ "findAndModify": "z", "query": { "name": "list1" }, "update": { "$push": { "a": 64 } }, "new": true })
{
        "lastErrorObject" : {
                "updatedExisting" : true,
                "n" : 1,
                "connectionId" : 65,
                "err" : null,
                "ok" : 1
        },
        "value" : {
                "_id" : ObjectId("4ee27202c469f4b2d3c6cbf9"),
                "a" : [ 
                        64
                ],
                "name" : "list1"
        },
        "ok" : 1
}
> db.z.find()
{ "_id" : ObjectId("4ee27202c469f4b2d3c6cbf9"), "a" : [ 64 ], "name" : "list1" }

You would then compute the index in client code. Note that subsequent operations MAY render this index invalid (i.e., a subsequent remove, $set, or $pull) -- handling this case is dependent on your application.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文