如何从MongoDB中的数组中删除对象?
您可以使用$pull运算符从MongoDB中的数组中删除对象。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.removeObjectFromArrayDemo.insertOne(
... {
...
... "StudentName": "John",
... "StudentAcademicProjectDetails":
... [{
... "StudentProjectId": 101,
... "StudentProjectName": "Pig Dice Game"
... },
... {
... "StudentProjectId": 110,
... "StudentProjectName": "Library Management System"
... },
...
... {
... "StudentProjectId": 120,
... "StudentProjectName": "Phonebook Management System"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817")
}在find()方法的帮助下显示集合中的所有文档。查询如下-
> db.removeObjectFromArrayDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 101,
"StudentProjectName" : "Pig Dice Game"
},
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
}这是从MongoDB中的数组中删除对象的查询-
> db.removeObjectFromArrayDemo.update(
... {'_id': ObjectId("5c8ad13d6cea1f28b7aa0817")},
... { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } },
... false,
... true
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })让我们检查集合中的文档以检查对象是否已从数组中删除。查询如下-
> db.removeObjectFromArrayDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
}查看上面的示例输出,删除了101的字段“StudentProjectId”。