Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to pull value from array of ObjectIDs in MongoDB?
To pull value from array of ObjectIDs in MongoDB, use the $pull operator with the $in operator to match and remove specific ObjectID values from the array.
Syntax
db.collection.update(
{ /* query */ },
{ $pull: { arrayField: { $in: [ObjectId("id1"), ObjectId("id2")] } } }
);
Sample Data
Let us create a collection with documents ?
db.demo258.insertOne({
"arrayOfObjectsId": [
ObjectId("5e47a5e81627c0c63e7dba92"),
ObjectId("5e47a5e51627c0c63e7dba91")
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e47a8211627c0c63e7dba97")
}
Display all documents from a collection with the help of find() method ?
db.demo258.find();
{
"_id": ObjectId("5e47a8211627c0c63e7dba97"),
"arrayOfObjectsId": [
ObjectId("5e47a5e81627c0c63e7dba92"),
ObjectId("5e47a5e51627c0c63e7dba91")
]
}
Example: Pull Specific ObjectID
Following is the query to pull value from array of ObjectIDs ?
db.demo258.update(
{ },
{ $pull: { arrayOfObjectsId: { $in: [ObjectId("5e47a5e81627c0c63e7dba92")] } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents from a collection with the help of find() method ?
db.demo258.find();
{
"_id": ObjectId("5e47a8211627c0c63e7dba97"),
"arrayOfObjectsId": [ObjectId("5e47a5e51627c0c63e7dba91")]
}
Conclusion
Use $pull with $in to remove specific ObjectID values from arrays. The $in operator allows matching multiple ObjectIDs in a single operation, making it efficient for removing multiple values.
Advertisements
