如何从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”。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短