Finding specific object(s) from multiple arrays and then do crud operations with Mongodb

Viewed 45

Here is a screenshot of my collection:

enter image description here

Here is my query:

db.collection("collection_name").aggregate(
[
{$match: 
{br_date: this.data.date}
}
]).toArray()

And, this is what I get

_id: id,
brdate: 10-08-2022
brName: "Principal Branch, Dhaka",
email: "example_email,
loans: [

[
{loan_id: 1, loan_name: X, category: "rural"},
{loan_id: 2, loan_name: Y, category: "urban"},
{loan_id: 3, loan_name: Z, category: "rural"}
],

[
{loan_id: 4, loan_name: A, category: "rural"},
{loan_id: 5, loan_name: B, category: "urban"}
],

]

Question 1: I would like to show the loans depending on their category. Let's say, I would like to show the loans that are from "rural" category. How do I do that?

Question 2: I may have to delete a loan that matches the loan_id. How do I do that?

Question 3: I may have to update a loan that matches the loan_id. How do I do that?

1 Answers

Since loans is an array of arrays I would use $[<i>] filtered positional operator: https://www.mongodb.com/docs/manual/reference/operator/update/positional-filtered/

1.

db.testie.aggregate([{
    $match: {
        _id: { $eq: ObjectId("62fb3af6a9b543178fb28bb5"), }
    }
}, {
    $unwind: '$loans'
}, {
    $unwind: '$loans'
}, {
    $group: { _id: "$loans.category", loanCategory: { $addToSet: '$loans' } }
}])
db.collection.updateOne({
    "_id" : id,
}, {
    $pull: { 'loans.$[]': { 'category': 'test_category' } }
});
db.collection.updateOne({
    "_id" : id,
}, {
    $set: { 'loans.$[].$[loan].category': 'test_category' }
}, {
    arrayFilters: [{ 'loan.loan_id': 3 }]
});

Aggregation: https://mongoplayground.net/p/8NmT6Qn3Wh7

Delete https://mongoplayground.net/p/LUDrpDLP6kN

Update https://mongoplayground.net/p/sRAvJiWOYmV

Related