user1513388
user1513388

Reputation: 7441

Updating collections from collections

I have 2 MongoDB Collections, collection 1 looks like this:

Coll1:

{
   _id: 123456789,
   isbn: "123456"
   title: "MongoDB: The Definitive Guide",
   author: [ "Kristina Chodorow", "Mike Dirolf" ],
   published_date: ISODate("2010-09-24"),
   pages: 216,
   language: "English",
   publisher_id: "oreilly"
}

{
   _id: 234567890,
   isbn: "456789"
   title: "50 Tips and Tricks for MongoDB Developer",
   author: "Kristina Chodorow",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher_id: "oreilly"
}

{
   _id: 234567891,
   isbn: "888222"
   title: "PostgreSQL: Up and Running",
   author: "Regina O. Obe, Leo S. Hsu",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher_id: "oreilly"
}

and collection2 looks like this:

Coll2:

{
  isbn: "123456",
  category: "NoSQL",
  gender: "male"
}

}
  isbn: "456789",
  category: "NoSQL",
  gender: "male"
}

}
  isbn: "888222",
  category: "SQL",
  gender: "male"
}

I need to iterate over all of the documents in collection 2, match the ISBN number in collection 1, then add the category field to the corresponding documents in collection 1.

e.g.

{
   _id: 234567891,
   isbn: "888222"
   title: "PostgreSQL: Up and Running",
   author: "Regina O. Obe, Leo S. Hsu",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher_id: "oreilly",
   category: "NoSQL"
}

What's the best way to achieve this using either the Mongo shell or maybe Python?

Upvotes: 0

Views: 55

Answers (1)

Andrei Beziazychnyi
Andrei Beziazychnyi

Reputation: 2917

In Mongo Shell you could use the following code:

db.Coll2.find().forEach(function(c2){ 
 db.Coll1.update({isbn:c2.isbn},{$set: {category:c2.category}},{multi:true})
});   

Upvotes: 0

Related Questions