MongoDBで条件付きアップサートまたは更新を実行します
条件付きのアップサートまたは更新には、$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での条件付きアップサートまたは更新のクエリです
> db.conditionalUpdatesDemo.update( { _id: 100 }, { $max: { "BiggestScore": 150 } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) フィールド「BiggestScore」が_id100の値150で更新されているかどうかを確認してみましょう
> 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
} -
MongoDBを使用した複数のアトミックアップデート?
複数のアトミック更新の場合は、$ setとともにupdate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo699.insertOne({Name:"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e370551299a9f98c93a7") } > db.demo699.insertOne({Name:"Da
-
MySQLで条件付きGROUPBYを実行してフェッチするにはどうすればよいですか?
まずテーブルを作成しましょう- mysql> create table DemoTable ( StudentName varchar(40), StudentMarks int ); Query OK, 0 rows affected (0.64 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql> insert into DemoTable values('John',78); Query OK, 1 row affected (0.14 sec) mysql> i