MongoDB query to remove element from array as sub property

MongoDBDatabaseBig Data Analytics

To remove, use $pull in MongoDB. Let us first create a collection with documents −

> db.demo388.insertOne(
...    {
...       _id: '101',
...       userDetails: {
...          isMarried: false,
...          userInfo: [
...             {
...                Name:"Chris",
...                Age:21
...
...             }
...          ]
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : "101" }

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

> db.demo388.find();

This will produce the following output −

{ "_id" : "101", "userDetails" : { "isMarried" : false, "userInfo" : [ { "Name" : "Chris", "Age" : 21 } ] } }

Following is the query to remove element from array as sub property −

> db.demo388.update(
...    { "_id": "101" },
...    { "$pull": { "userDetails.userInfo": { "Name":"Chris" } }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo388.find();

This will produce the following output −

{ "_id" : "101", "userDetails" : { "isMarried" : false, "userInfo" : [ ] } }
raja
Published on 02-Apr-2020 17:24:23
Advertisements