推送后获取索引
使用 $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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不会是原子的。执行此类操作的最佳方法是使用 findAndModify:
http://www.mongodb。 org/display/DOCS/findAndModify+Command
这是一个自动应用 $push 更新并返回结果文档的示例。请注意,findAndModify 调用返回应用了推送的“新”文档。这是原子的。
然后,您将在客户端代码中计算索引。请注意,后续操作可能会导致该索引无效(即后续的删除、$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.
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.