根据两个条件更新 MongoDB 中的数量?
为此,请使用 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();
这会生成以下输出:&mnus;
{ "_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
}
]
}
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP