在 MongoDB 中执行条件 upsert 或更新


对于条件 upsert 或更新,可以使用 $max 运算符。我们首先使用文档创建一个集合

>db.conditionalUpdatesDemo.insertOne({"_id":100,"StudentFirstScore":89,"StudentSecondScore":78,"BiggestScore":89});
{ "acknowledged" : true, "insertedId" : 100 }
>db.conditionalUpdatesDemo.insertOne({"_id":101,"StudentFirstScore":305,"StudentSecondScore":560,"BiggestScore":1050});
{ "acknowledged" : true, "insertedId" : 101 }
>db.conditionalUpdatesDemo.insertOne({"_id":103,"StudentFirstScore":560,"StudentSecondScore":789,"BiggestScore":880});
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from a collection with the help of find() method:
> db.conditionalUpdatesDemo.find().pretty();

这将生成以下输出

{
   "_id" : 100,
   "StudentFirstScore" : 89,
   "StudentSecondScore" : 78,
   "BiggestScore" : 89
}
{
   "_id" : 101,
   "StudentFirstScore" : 305,
   "StudentSecondScore" : 560,
   "BiggestScore" : 1050
}
{
   "_id" : 103,
   "StudentFirstScore" : 560,
   "StudentSecondScore" : 789,
   "BiggestScore" : 880
}

以下是 MongoDB 中条件 upsert 或更新的查询

> db.conditionalUpdatesDemo.update( { _id: 100 }, { $max: { "BiggestScore": 150 } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

让我们检查一下字段“BiggestScore”是否使用值 150 更新了 _id 100

> db.conditionalUpdatesDemo.find().pretty();

这将生成以下输出

{
   "_id" : 100,
   "StudentFirstScore" : 89,
   "StudentSecondScore" : 78,
   "BiggestScore" : 150
}
{
   "_id" : 101,
   "StudentFirstScore" : 305,
   "StudentSecondScore" : 560,
   "BiggestScore" : 1050
}
{
   "_id" : 103,
   "StudentFirstScore" : 560,
   "StudentSecondScore" : 789,
   "BiggestScore" : 880
}

更新于:2019 年 7 月 30 日

111 次浏览

开启您的事业

通过完成课程获得认证

开始
广告
© . All rights reserved.