为此,请使用UPDATE()方法,并在其中设置两个条件。让我们创建一个包含文档的集合-
> db.demo605.insertOne( ... { ... _id:1, ... "Information" : [ ... { ... "id" : "Product-1", ... "Quantity" : 50, ... }, ... { ... "id" : "Product-2", ... "Quantity" : 100, ... }, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 1 } > > > db.demo605.insertOne( ... { ... _id:2, ... "Information" : [ ... { ... "id" : "Product-1", ... "Quantity" : 30, ... }, ... { ... "id" : "Product-2", ... "Quantity" : 40, ... }, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 2 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo605.find();
这将产生以下输出;
{ "_id" : 1, "Information" : [ { "id" : "Product-1", "Quantity" : 50 }, { "id" : "Product-2", "Quantity" : 100 } ] } { "_id" : 2, "Information" : [ { "id" : "Product-1", "Quantity" : 30 }, { "id" : "Product-2", "Quantity" : 40 } ] }
以下是根据两个条件更新MongoDB中数量的查询-
>db.demo605.update({_id:1,"Information.id":"Product1"}, {$set:{"Information.$.Quantity":1000}} ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo605.find().pretty();
这将产生以下输出-
{ "_id" : 1, "Information" : [ { "id" : "Product-1", "Quantity" : 1000 }, { "id" : "Product-2", "Quantity" : 100 } ] } { "_id" : 2, "Information" : [ { "id" : "Product-1", "Quantity" : 30 }, { "id" : "Product-2", "Quantity" : 40 } ] }