Home > Database > MongoDB > body text

Remove array elements from MongoDB collection using update() and $pull

WBOY
Release: 2023-09-13 16:45:09
forward
1351 people have browsed it

使用 update() 和 $pull 从 MongoDB 集合中删除数组元素

Let us first create a collection containing documents -

> db.removingAnArrayElementDemo.insertOne({"UserMessage":["Hi","Hello","Bye"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cef97bdef71edecf6a1f6a4")
}
Copy after login

Display all the documents in the collection with the help of find() method -

> db.removingAnArrayElementDemo.find().pretty();
Copy after login
Copy after login

Output

{
   "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"),
   "UserMessage" : [
      "Hi",
      "Hello",
      "Bye"
   ]
}
Copy after login

The following is the query to delete array elements from MongoDB -

> db.removingAnArrayElementDemo.update(
   {_id:ObjectId("5cef97bdef71edecf6a1f6a4")},
   { "$pull": { "UserMessage": "Hello" } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Copy after login

Let’s check the document again:

> db.removingAnArrayElementDemo.find().pretty();
Copy after login
Copy after login

Output

{
   .
   "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"),
   "UserMessage" : [
      "Hi",
      "Bye"
   ]
}
Copy after login

The above is the detailed content of Remove array elements from MongoDB collection using update() and $pull. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template