我有2个MongoDB集合,集合1看起来像这样:
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"
}
和collection2看起来像这样:
Coll2:
{
isbn: "123456",
category: "NoSQL",
gender: "male"
}
}
isbn: "456789",
category: "NoSQL",
gender: "male"
}
}
isbn: "888222",
category: "SQL",
gender: "male"
}
我需要迭代集合2中的所有文档,匹配集合1中的ISBN号,然后将类别字段添加到集合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"
}
使用Mongo shell或Python可以实现此目的的最佳方法是什么?
答案 0 :(得分:0)
在Mongo Shell中,您可以使用以下代码:
db.Coll2.find().forEach(function(c2){
db.Coll1.update({isbn:c2.isbn},{$set: {category:c2.category}},{multi:true})
});