365Tools
发布时间:2024-03-30 14:30:01
维护原子性的推荐方法是保留所有相关信息,并将这些信息使用嵌入式文档的形式更新到文档中,这将确保单个文档的所有更新都是原子的。假设我们已经创建了一个名为 productDetails 的集合,并在其中插入了一个文档,如下所示:
> db.productDetails.insert(
... {
... "product_name": "Samsung S3",
... "category": "mobiles",
... "product_total": 5,
... "product_available": 3,
... "product_bought_by": [
... {
... "customer": "john",
... "date": "7-Jan-2014"
... },
... {
... "customer": "mark",
... "date": "8-Jan-2014"
... }
... ]
... }
... )
WriteResult({ "nInserted" : 1 })
在上面的文档中,我们将购买产品的客户的信息嵌入到 product_bought_by 字段中。当有新客户购买该产品时,我们首先会使用 product_available 字段检查该产品是否仍然可用。如果可用,我们就减少 product_available 字段的值,并在 product_bought_by 字段中插入新客户的信息。
> db.productDetails.findAndModify({query:{_id:ObjectId("603f31435e514debed504a38"), product_available:{$gt:0}}, update:{$inc:{product_available:-1}, $push:{product_bought_by:{customer:"rob", date:"9-Jan-2014"}}}})
{
"_id" : ObjectId("603f31435e514debed504a38"),
"product_name" : "Samsung S3",
"category" : "mobiles",
"product_total" : 5,
"product_available" : 3,
"product_bought_by" : [
{
"customer" : "john",
"date" : "7-Jan-2014"
},
{
"customer" : "mark",
"date" : "8-Jan-2014"
}
]
}
上面的示例中我们使用 findAndModify 来查询并更新文档,这样可以确保只有在产品可用时才更新产品购买信息。而且整个过程都在同一个查询中完成。{ $set : { field : value } }
{ $unset : { field : 1} }
{ $inc : { field : value } }
{ $push : { field : value } }
把 value 追加到 field 里面去,field 一定要是数组类型才行,如果 field 不存在,则会新增一个数组类型加进去。{ $pushAll : { field : value_array } }
{ $pull : { field : _value } }
{ $pop : { field : 1 } }
{ $rename : { old_field_name : new_field_name } }
{$bit : { field : {and : 5}}}
> t.find() { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )
> t.find() { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }