仅在MongoDB中的值唯一时插入,否则更新
您可以使用upsert,即,只要您插入一个值并且该值已经存在,便会执行更新。如果该值尚不存在,则将其插入。
首先让我们创建一个包含文档的集合
> 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
}