根據兩個條件更新 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