在MongoDB中,$ addToSet与“ $ removeFromSet”相反吗?
要将相反的$addToSet设置为'$removeFromSet',请使用$pull运算符。
让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.oppositeAddToSetDemo.insertOne({"StudentName":"John","StudentHobby":["Cricket","Cooking","Drawing"]});{
"acknowledged" : true,
"insertedId" : ObjectId("5c8eddcc2f684a30fbdfd588")
}
> db.oppositeAddToSetDemo.insertOne({"StudentName":"Carol","StudentHobby":["Cricket","Dance","Hiking"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8eddfd2f684a30fbdfd589")
}
> db.oppositeAddToSetDemo.insertOne({"StudentName":"David","StudentHobby":["Learning","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ede272f684a30fbdfd58a")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.oppositeAddToSetDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c8eddcc2f684a30fbdfd588"),
"StudentName" : "John",
"StudentHobby" : [
"Cricket",
"Cooking",
"Drawing"
]
}
{
"_id" : ObjectId("5c8eddfd2f684a30fbdfd589"),
"StudentName" : "Carol",
"StudentHobby" : [
"Cricket",
"Dance",
"Hiking"
]
}
{
"_id" : ObjectId("5c8ede272f684a30fbdfd58a"),
"StudentName" : "David",
"StudentHobby" : [
"Learning",
"Photography"
]
}
这是使用$pull运算符查询$addToSet与'$removeFromSet'相反的对象-
> db.oppositeAddToSetDemo.update(... {"StudentName": "John"},
... {$pull: { "StudentHobby": "Cooking"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们使用来检查集合中的文档find()
。查询如下:
> db.oppositeAddToSetDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c8eddcc2f684a30fbdfd588"),
"StudentName" : "John",
"StudentHobby" : [
"Cricket",
"Drawing"
]
}
{
"_id" : ObjectId("5c8eddfd2f684a30fbdfd589"),
"StudentName" : "Carol",
"StudentHobby" : [
"Cricket",
"Dance",
"Hiking"
]
}
{
"_id" : ObjectId("5c8ede272f684a30fbdfd58a"),
"StudentName" : "David",
"StudentHobby" : [
"Learning",
"Photography"
]
}
以上是 在MongoDB中,$ addToSet与“ $ removeFromSet”相反吗? 的全部内容, 来源链接: utcz.com/z/326935.html