使用公式更新集合中檔案的每個欄位的 MongoDB 查詢?
若要使用公式更新集合中檔案的每個欄位,請使用 MongoDB update()。我們建立一個包含以下文件的集合:
> db.demo749.insertOne({"details":[{"id":1,a:10},{"id":2,a:5},{"id":3,a:20}]}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6fb0a930c785c834e565") }
使用 find() 方法顯示集合中的所有文件:
> db.demo749.find().pretty();
這將生成以下輸出:
{ "_id" : ObjectId("5eae6fb0a930c785c834e565"), "details" : [ { "id" : 1, "a" : 10 }, { "id" : 2, "a" : 5 }, { "id" : 3, "a" : 20 } ] }
以下是使用公式更新集合中檔案的每個欄位的查詢:
> db.demo749.update( ... { ... ... }, ... { ... $mul: { "details.$[].a": 2/5} ... }, ... { multi:true} ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
使用 find() 方法顯示集合中的所有文件:
> db.demo749.find().pretty();
這將生成以下輸出:
{ "_id" : ObjectId("5eae6fb0a930c785c834e565"), "details" : [ { "id" : 1, "a" : 4 }, { "id" : 2, "a" : 2 }, { "id" : 3, "a" : 8 } ] }
廣告