0 votes
in MongoDB by
Updating a specific key/value inside of an array field with MongoDB

1 Answer

0 votes
by
{

“_id” : ObjectId(“4c1a5a948ead0e4d09010000”),

“authors” : [

{

“user_id” : null,

“slug” : “joe-somebody”,

“display_name” : “Joe Somebody”,

“display_title” : “Contributing Writer”,

“display_company_name” : null,

“email” : null,

“phone” : null,

“fax” : null,

“address” : null,

“address2” : null,

“city” : null,

“state” : null,

“zip” : null,

“country” : null,

“image” : null,

“url” : null,

“blurb” : null

},

{

“user_id” : null,

“slug” : “jane-somebody”,

“display_name” : “Jane Somebody”,

“display_title” : “Editor”,

“display_company_name” : null,

“email” : null,

“phone” : null,

“fax” : null,

“address” : null,

“address2” : null,

“city” : null,

“state” : null,

“zip” : null,

“country” : null,

“image” : null,

“url” : null,

“blurb” : null

},

],

“tags” : [

“tag1”,

“tag2”,

“tag3”

],

“title” : “Title of the Article”

}

I can find every article that this author has created by running the following command:

1

db.content.find({authors: {$elemMatch: {slug: ‘joe-somebody’}}});

So theoretically I should be able to update the author's record for the slug joe-somebody but notjane-somebody (the 2nd author), I am just unsure exactly how you reach in and update every record for that author.

I thought I was on the right track, and here’s what I’ve tried.

“_id” : ObjectId(“4c1a5a948ead0e4d09010000”),

“authors” : [

{

“user_id” : null,

“slug” : “joe-somebody”,

“display_name” : “Joe Somebody”,

“display_title” : “Contributing Writer”,

“display_company_name” : null,

“email” : null,

“phone” : null,

“fax” : null,

“address” : null,

“address2” : null,

“city” : null,

“state” : null,

“zip” : null,

“country” : null,

“image” : null,

“url” : null,

“blurb” : null

},

{

“user_id” : null,

“slug” : “jane-somebody”,

“display_name” : “Jane Somebody”,

“display_title” : “Editor”,

“display_company_name” : null,

“email” : null,

“phone” : null,

“fax” : null,

“address” : null,

“address2” : null,

“city” : null,

“state” : null,

“zip” : null,

“country” : null,

“image” : null,

“url” : null,

“blurb” : null

},

],

“tags” : [

“tag1”,

“tag2”,

“tag3”

],

“title” : “Title of the Article”

}

Solution:

This is what finally worked for me!

1

db.content.update({‘authors.slug’:’joe-somebody’},{$set:{‘authors.$.address’:’Address That I wanted’}},false,true);

It updates all the records properly, thanks!

Maybe you can use the $ operator (positional-operator) in MongoDB?

Related questions

+1 vote
asked Aug 24, 2020 in MongoDB by Hodge
0 votes
asked Jun 3, 2020 in MongoDB by Robindeniel
...