English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode recommandée pour maintenir l'atomicité est de conserver toutes les informations pertinentes, qui sont souvent mises à jour ensemble dans un document par l'intermédiaire de documents intégrés. Cela garantit que toutes les mises à jour du document unique sont atomiques.
Supposons que nous ayons déjà créé une collection nommée productDetails et y avons inséré un document, comme suit-
>db.createCollection("products") { "ok" : 1 } > db.productDetails.insert( { "_id":1, "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 ) >
Dans ce document, nous intégrons les informations des clients achetant des produits dans le champ product_bought_by. Chaque fois qu'un nouveau client achète un produit, nous vérifions d'abord si le produit est toujours disponible en utilisant le champ product_available. Si il est disponible, nous réduisons la valeur du champ product_available et insérons le document intégré du nouveau client dans le champ product_bought_by. Nous utilisons la commande findAndModify pour cette fonction, car le processus de recherche et de mise à jour des documents est le même.
>db.products.findAndModify({ query:{_id:2,product_available:{$gt:0}}, update:{ $inc:{product_available:-1}, $push:{product_bought_by:{customer:"rob",date:"9-Jan-2014"}} } )
We adopt the method of embedding documents and using findAndModify queries to ensure that the product purchase information is only updated when the product is available. The entire transaction is atomic and within the same query.
On the contrary, consider the following situation: we may separately retain the availability of the product and information about who purchased the product. In this case, we will use the first query to check the availability of the product first. Then, in the second query, we will update the purchase information. However, it is possible that other users have already purchased the product and it is no longer available between the execution of these two queries. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have already sold an unavailable product.