値がMongoDBで一意である場合にのみ挿入し、それ以外の場合は更新します
アップサートを使用できます。つまり、値を挿入し、その値がすでに存在する場合はいつでも、更新が実行されます。値がまだ存在しない場合は、挿入されます。
まず、ドキュメントを使用してコレクションを作成しましょう
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Larry","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a633815e86fd1496b38a4")
}
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Mike","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a634a15e86fd1496b38a5")
}
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Sam","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a635015e86fd1496b38a6")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
これにより、次の出力が生成されます
{
"_id" : ObjectId("5c9a633815e86fd1496b38a4"),
"StudentName" : "Larry",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9a634a15e86fd1496b38a5"),
"StudentName" : "Mike",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9a635015e86fd1496b38a6"),
"StudentName" : "Sam",
"StudentAge" : 24
} ケース1 :以下は、値がすでに存在する場合のクエリです。挿入する値はすでに存在するため、更新されます
> db.onlyInsertIfValueIsUniqueDemo.update({StudentName:"Mike"},{$set:{"StudentAge":27}},{ upsert: true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) すべてのドキュメントをもう一度見てください。以下はクエリです
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
これにより、次の出力が生成されます
{
"_id" : ObjectId("5c9a633815e86fd1496b38a4"),
"StudentName" : "Larry",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9a634a15e86fd1496b38a5"),
"StudentName" : "Mike",
"StudentAge" : 27
}
{
"_id" : ObjectId("5c9a635015e86fd1496b38a6"),
"StudentName" : "Sam",
"StudentAge" : 24
} ケース2 :以下は、値が一意である場合のクエリです。挿入する値はまだ存在しないため、挿入されます
>db.onlyInsertIfValueIsUniqueDemo.update({StudentName:"David"},{$set:{"StudentAge":25}},{ upsert: true});
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5c9a654ce628c11759caea54")
}) すべてのドキュメントをもう一度見てください。以下はクエリです
> db.onlyInsertIfValueIsUniqueDemo.find().pretty();
これにより、次の出力が生成されます
{
"_id" : ObjectId("5c9a633815e86fd1496b38a4"),
"StudentName" : "Larry",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9a634a15e86fd1496b38a5"),
"StudentName" : "Mike",
"StudentAge" : 27
}
{
"_id" : ObjectId("5c9a635015e86fd1496b38a6"),
"StudentName" : "Sam",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c9a654ce628c11759caea54"),
"StudentName" : "David",
"StudentAge" : 25
} -
MongoDBドキュメントの値を1つだけインクリメントしますか?
単一の値のみを更新してMongoDBでインクリメントするには、update()とともに$incを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo698.insertOne({Score:78}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8a4551299a9f98c9398") } > db.demo698.insertOne({Score:56}); { &nbs
-
MySQLの単一の列値のみを更新します
まずテーブルを作成しましょう- mysql> create table DemoTable1605 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentCountryName varchar(20) -> ); Query OK, 0 rows affected (0.48 sec) 挿入