MongoDB学习第无篇 --- Update操作

Posted MalcolmF

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB学习第无篇 --- Update操作相关的知识,希望对你有一定的参考价值。

数据如下:

db.inventory.insertMany( [
   { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
   { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
   { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
]);

 

一、shell执行update语句

# 更新一条document
db.inventory.updateOne( { item:
"paper" }, { $set: { "size.uom": "cm", status: "P" }, $currentDate: { lastModified: true } } )
# 更新多条document db.inventory.updateMany( {
"qty": { $lt: 50 } }, { $set: { "size.uom": "in", status: "P" }, $currentDate: { lastModified: true } } )
# 替换一条 document db.inventory.replaceOne( { item:
"paper" }, { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] } )

 

二、python操作update语句

# 更新一条document
db.inventory.update_one(
    {"item": "paper"},
    {
    "$set": {"size.uom": "cm", "status": "P"},
      "$currentDate": {"lastModified": True}
   }
)
# 更新多条document
db.inventory.update_many(
    {"qty": {"$lt": 50}},
    {
     "$set": {"size.uom": "in", "status": "P"},
        "$currentDate": {"lastModified": True}
    }
)
# 替换document
db.inventory.replace_one(
    {"item": "paper"},
    {
       "item": "paper",
       "instock": [
         {"warehouse": "A", "qty": 60},
         {"warehouse": "B", "qty": 40}
    ]
    }
)

 

 

三、Java操纵update语句

#  更新一条document
collection.updateOne(eq("item", "paper"),combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));
#  更新多条document
collection.updateMany(lt("qty", 50),combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified"))); 
#  替换document
collection.replaceOne(eq("item", "paper"),Document.parse("{ item: ‘paper‘, instock: [ { warehouse: ‘A‘, qty: 60 }, { warehouse: ‘B‘, qty: 40 } ] }"));

 





以上是关于MongoDB学习第无篇 --- Update操作的主要内容,如果未能解决你的问题,请参考以下文章

#千锋逆战班,1902#

mongodb高级操作-update

mongoDB 学习七

mongodb update 字符 操作

Mongodb数据更新命令操作符

mongodb更新操作