如何从 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"
      }
   ]
}

查看上述示例输出,ID 为 101 的 “StudentProjectId” 字段已移除。

更新于:30-Jul-2019

2 千次浏览

开启你的职业生涯 生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.