Search This Blog

2023/05/17

MongoDb: Manipulating array inside document

Today we will try to understand how to work with with array inside
a document in MongoDb.

We will use "locationWiseStundentInInstitute" collection for that
purpose.

Lets first drop the collection if any so that we can start fresh.

//drop database
db.locationWiseStundentInInstitute.drop()

Insert some documents into our collection "locationWiseStundentInInstitute"

//create a collection with data
db.locationWiseStundentInInstitute.insertMany(
[
{
_id: 1,
location: "Mumbai",
students: [
{
name: "arjun",
age: 5,
email: "arjun.sawant@example.com",
fees: 15000,
scholarship: 2000,
paid: 0,
subject: [
"AWS",
"Google Cloud",
"Microsoft Azure",
],
marks: [75, 97, 49],
},
{
name: "sita",
age: 30,
email: "sita@example.com",
fees: 15000,
scholarship: 1000,
paid: 2000,
subject: [
"AWS",
"Google Cloud",
"Microsoft Azure",
],
marks: [70, 70, 89],
},
],
},
{
_id: 2,
location: "Pune",
students: [
{
name: "anil",
age: 5,
email: "anil@example.com",
fees: 15000,
scholarship: 3000,
paid: 1000,
subject: [
"AWS",
"Google Cloud",
"Microsoft Azure",
],
marks: [55, 47, 89],
},
{
name: "arjun",
age: 5,
email: "arjun.patil@example.com",
fees: 15000,
scholarship: 2000,
paid: 0,
subject: [
"AWS",
"Google Cloud",
"Microsoft Azure",
],
marks: [85, 67, 89],
},
{
name: "sunil",
age: 30,
email: "sunil@example.com",
fees: 15000,
scholarship: 1000,
paid: 0,
subject: [
"AWS",
"Google Cloud",
"Microsoft Azure",
],
marks: [40, 90, 59],
},
],
},
]
);

Condition 1:
Now suppose student "arjun.sawant@example.com" has submitted his B.E.
education certificate we need to save this data.

We need to run following query:

db.locationWiseStundentInInstitute.updateOne(
{ "students.email": "arjun.sawant@example.com" },
{ $set: { "students.$.education": ["B.E."] } }
);

Here against education an array ["B.E"] is saved.

If instead of array we saved only a string "B.E." that also will work,
Below is query for the same.

db.locationWiseStundentInInstitute.updateOne(
{ "students.email": "arjun.sawant@example.com" },
{ $set: { "students.$.education": "B.E." } }
);

Condition 2:
Lets assume that if a user with email id "anil@example.com" want his email id
to be changed to "anil@gmail.com" then that can be done as

//update existing property in matched object array element
db.locationWiseStundentInInstitute.updateOne(
{ "students.email": "anil@example.com" },
{ $set: { "students.$.email": "anil@gmail.com" } }
);

Suppose we want to add name of instructor for each elements of students array
in document where "sunil@example.com" is present then run following query

//add tag to all elements of array
db.locationWiseStundentInInstitute.updateOne(
{"students.email": 'sunil@example.com' },
{ $set: { "students.$[].instructor": "K C Muzumdar" } }
);


No comments:

Post a Comment