Update multiple doc in nested array

mongodb

#1

I have a collection “team_member” like this

{
"_id" : ObjectId("5c0e0d63421aa95f61da6f6a"),
"teams" : [
	{
		"allowedToAddComment" : true,
		"teamId" : ObjectId("5c0a5d5b421aa91ac4fe5095"),
	},
	{
		"allowedToAddComment" : true,
		"teamId" : ObjectId("5c0e0d53421aa95f6185e967"),
	}
  ],
  "userId" : ObjectId("5c0e0d52421aa95f61b0a931")
}
{
	"_id" : ObjectId("5c0e0d63421aa95f61da5d5a"),
	"teams" : [
		{
			"allowedToAddComment" : true,
			"teamId" : ObjectId("5c0a5d5b421aa91ac4fe5095"),
		},
		{
			"allowedToAddComment" : true,
			"teamId" : ObjectId("5c0e0d63421aa95f61da5d5b"),
		}
	],
	"userId" : ObjectId("5c0e0d63421aa95f61da5d59")
}

Now I need to update “allowedToAddComment” : false for “teams.teamId”: ObjectId("5c0a5d5b421aa91ac4fe5095"). for all the document. How can i achieve that??


#2

You will want to use the $[<identifier>] operator. Your query should look something like

db.collect.updateMany(
  {},
  {$set: {"teams.$[elem].allowedToAddComment" : false}},
  {
  multi: true,
  arrayFilters: [{"elem.teamId": ObjectId("5c0a5d5b421aa91ac4fe5095")}]
  })

Unfortunately it looks like the mongodb package does not currently support the arrayFilters option. I will see if I can get something for that working.