Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Pull Value from Array of ObjectIDs in MongoDB



To pull value from array of ObjectIDs, use $pull in MongoDB. 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();

This will produce the following output −

{ "_id" : ObjectId("5e47a8211627c0c63e7dba97"), "arrayOfObjectsId" : [ ObjectId("5e47a5e81627c0c63e7dba92"), ObjectId("5e47a5e51627c0c63e7dba91") ] }

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 })

Display all documents from a collection with the help of find() method −

> db.demo258.find();

This will produce the following output −

{ "_id" : ObjectId("5e47a8211627c0c63e7dba97"), "arrayOfObjectsId" : [ ObjectId("5e47a5e51627c0c63e7dba91") ] }
Updated on: 2020-03-31T08:19:39+05:30

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements