Ad Code

Responsive Advertisement

✨ MongoDB - Array

📘 MongoDB Array Operations – Detailed Notes

🔸 1. Creating Documents with Arrays

db.users.insertOne({
  name: "Ashutosh",
  age: 21,
  score: [34, 56, 89]
});

🔸 2. Querying Arrays

✅ Match a Document That Contains a Specific Array Value

db.users.find({ score: 56 });

✅ Match an Exact Array (Order + Values Must Match)

db.users.find({ score: [34, 56, 89] });

✅ Match Documents Based on Array Length

db.users.find({ score: { $size: 3 } });

🔸 3. Updating Arrays

✅ Update Specific Index in an Array

db.users.updateOne(
  { age: 21 },
  { $set: { "score.1": 99 } }
);

MongoDB will not update if the value is the same as existing — modifiedCount will be 0.

🔸 4. Add Elements to Arrays

✅ Add One Element

db.users.updateOne(
  { age: 21 },
  { $push: { score: 77 } }
);

✅ Add Multiple Elements

db.users.updateOne(
  { age: 21 },
  { $push: { score: { $each: [68, 71] } } }
);

🔸 5. Remove Elements from Arrays

✅ Remove a Specific Value

db.users.updateOne(
  { age: 21 },
  { $pull: { score: 34 } }
);

✅ Remove Multiple Values

db.users.updateOne(
  { age: 21 },
  { $pullAll: { score: [56, 89] } }
);

🔸 6. Other Array Operators

Operator Description
$push Adds element(s) to an array
$pop Removes first (-1) or last (1) element
$pull Removes matching elements
$each Used with $push/$addToSet to add multiple items

🧠 Tips

  • Indexing in arrays starts at 0.
  • Use $size to query arrays by length.
  • MongoDB won't update if new value is the same as old value.

Post a Comment

0 Comments