将两个mongoDB集合合并为一个的最佳方法

时间:2014-06-26 19:32:36

标签: mongodb

我有两个名为users和users_custom的mongoDB集合。例如:用户集合如下所示:

{
    "_id" : ObjectId("53ac64d445fa47e97a5f3b50"),
    "user_id" : "1",
    "Name" : "Mr. A",
    "phone" : "12345"
}
{
    "_id" : ObjectId("53ac64e145fa47e97a5f3b53"),
    "user_id" : "2",
    "Name" : "Mr. B",
    "phone" : "23456"
}

users_custom集合如下所示:

{
    "_id" : ObjectId("53ac64d445fa47e97a5f3b32"),
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "email" : "someone@gmail.com"
}
{
    "_id" : ObjectId("53ac64e145fa47e97a5f3b232"),
    "user_id" : "2",
    "Name" : "Mr. B",
    "address" : "some address"
}

我想将用户集合上的users_custom集合合并到users_final集合中。这样看起来会像:

{
    "_id" : ObjectId("53ac64d445fa47e97a5f3b32"),
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "phone" : "12345"
    "email" : "someone@gmail.com"
}
{
    "_id" : ObjectId("53ac64e145fa47e97a5f3b232"),
    "user_id" : "2",
    "Name" : "Mr. B",
    "phone" : "23456"
    "address" : "some address"
} 

任何想法或示例代码将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您要尝试做的是加入两个集合。 MongoDB本身并不支持连接,但是通过map reduce框架可以实现连接功能。这可能需要一段时间,应该离线完成,而不是作为实时查询。

这些问题/文章应该提供一些指导:

MongoDB: Combine data from multiple collections into one..how?

Merging two collections in MongoDB

http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/