Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Pull multiple objects from an array

Tags:

arrays

mongodb

Hi I'm trying to remove multiple objects from an array that looks like this.

{
"_id" : ObjectId("5a7da1bda21d5f3e8cf005b3"),
"owner" : "1",
"group_name" : "PAASCU Board",
"group_members" : [ 
    {
        "faculty_name" : "Cheska Dela Rosa",
        "faculty_number" : 2,
        "_id" : ObjectId("5a7da1bda21d5f3e8cf005b5")
    }, 
    {
        "faculty_name" : "Earl Sempio",
        "faculty_number" : 7323,
        "_id" : ObjectId("5a7da1bda21d5f3e8cf005b4")
    }, 
    {
        "faculty_number" : 203,
        "faculty_name" : "Sample",
        "_id" : ObjectId("5a7dbf7952bd150a94d83958")
    }, 
    {
        "faculty_number" : 8025,
        "faculty_name" : "Sample Postman",
        "_id" : ObjectId("5a7dc64a1cf5dd3d50167d53")
    }
],
"__v" : 0 }

It works when I remove a single object using the $pull with this code.

db.getCollection('groups').update({_id: ObjectId("5a7da1bda21d5f3e8cf005b3")}, {$pull: {"group_members": {"faculty_number":8025}}})

But what if I want to remove multiple objects with different faculty_number? I tried using the $each method just like how I add multiple objects in the array but it doesn't work well.

like image 518
Patrick Ian Co Avatar asked Feb 09 '18 16:02

Patrick Ian Co


People also ask

How do I pull all elements in an array in MongoDB?

The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.

What is $Set in MongoDB?

$set outputs documents that contain all existing fields from the input documents and newly added fields. The $set stage is an alias for $addFields. Both stages are equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.

How do I use $Push in MongoDB?

If the field is absent in the document to update, $push adds the array field with the value as its element. If the field is not an array, the operation will fail. If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push .


1 Answers

Use $in operator to pass the list of faculty values to remove documents from embedded array. More here

Try

db.groups.update(
  {"_id": ObjectId("5a7da1bda21d5f3e8cf005b3")},
  {"$pull":{"group_members":{"faculty_number":{$in:[8025,7323]}}}}
)
like image 100
s7vr Avatar answered Oct 26 '22 20:10

s7vr