Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7664

MongoDB query for two input arrays at same index?

I have two arrays A and B of length n defined by the input,

fruit_ids = [{id: "id1"}, {id: "id2"}, {id:"id3"}]; fruit_names = [{name: "Orange"},{name: "Kiwi"},{name: "Banana"}]

and MongoDB documents

{ farm_id: "3344", fruits: [{name: "Orange", id:"id1"}, {name: "Kiwi", id:"id67"}]}

Now I want to write a Mongo query such that it pulls items from particular farm_id specified at array fruit_ids and fruit_names but at same index,

for example for the above input, I want for farm_id: 3344 {name: "Orange", id:"id1"} to get deleted.

Can anyone please help me.

Upvotes: 1

Views: 73

Answers (2)

Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7664

I was trying $pullAll as suggested by @mickl in his answer, but the thing is I had other fields inside my embedded documents and because $pullAll works only for exact matches, that's why I currently I am using $pull with $or on the array of embedded docs. I found this solution from this answer how-to-force-mongodb-pullall-to-disregard-document-order.

let arr = [{name: "Orange", id:"id1"}, {name: "Kiwi", id:"id67"}];

db.col.update(
    { farm_id: 3344 },
    { "$pull": { "fruits": { "$or": arr } }}
)

Upvotes: 0

mickl
mickl

Reputation: 49945

You can use $pullAll operator to remove all the matching elements and build your update statement dynamically using below code:

var fruit_ids = [{id: "id1"}, {id: "id2"}, {id:"id3"}]; 
var fruit_names = [{name: "Orange"},{name: "Apple"},{name: "Banana"}];

var pullAll = {
    $pullAll: { fruits: fruit_ids.map((id, index) => Object.assign(fruit_names[index], id)) }
}

db.col.update({ farm_id: 3344 }, pullAll)

This will only try to update the farm_id: 3344.

Upvotes: 1

Related Questions