前提:更新语句是无害的,因为驱动程序默认情况下以一种消息传递方式工作(只要getLastError
不使用)。
问题以下片段是在 mongodb 中进行大容量插入的最佳方法吗?是否可以折叠第 2 步和第 3 步?
编辑:旧的越野车形式,见下文
// step 1 : making sure the top-level document is present (an upsert in the real
example)
db.test.insert( { x :1} )
// step 2 : making sure the sub-document entry is present
db.test.update( { x:1 }, { "$addToSet" : { "u" : { i : 1, p : 2 } } }, false)
// step 3 : increment a integer within the subdocument document
db.test.update( { x : 1, "u.i" : 1}, { "$inc" : { "u.$.c" : 1 } },false)
我有一种感觉没有办法退出操作 3,因为$
操作员需要在更新的查询部分的查询字段中启动。阿米特?亚美特?
如果这是做事的最佳方式,我可以在我的代码中发挥创意并在更新操作上发疯吗?
编辑:新表格
我的逻辑中有一个错误,谢谢盖茨。如果可能的话,仍然想折叠更新:D
// make sure the top-level entry exists and increase the incidence counter
db.test.update( { x : 1 }, { $inc : { i : 1 } }, true ) --1
// implicetly creates the array
db.test.update( { x : 1 , u : { $not : { $elemMatch : { i : 1 } } } } ,
{ $push : { u : { i : 1 , p :2 , c:0} } }) -- 2
db.test.update( { x :1 , "u.i" : 1}, { $inc : { "u.$.c" : 1 } },false) --3
注意:$addToSet
在这种情况下没有用,因为它进行元素匹配,所以无法mutable
像 C++ OO 按位比较用语那样表达数组中的哪些元素
问题毫无意义数据模型错误。请投票关闭(OP)。