I need to merge two collections into one, but I need to put the document only if it doesn't exists in the first collection. How can I do it? What's the best way? I saw something about agregation and mapreduce but I am not sure about what to use. Can you help me, please?
Asked
Active
Viewed 1,688 times
2
-
Check out this question http://stackoverflow.com/questions/9696940/merging-two-collections-in-mongodb – blackmind Oct 13 '14 at 18:47
2 Answers
2
I think there is no automatic way for that. Assume u have 2 collection for merge, c1 and c2 You could manually do the merge with
db.c1.find().forEach(function(item) {
db.c2.insert(item);
db.c1.remove(item);
});
u should be careful with that because mongo does not support multi-document-transaction

Disposer
- 6,201
- 4
- 31
- 38
1
This is the simplest brute-force approach that comes to my mind.
Below, users
is the collection to which you are going to copy documents from users2
. I am assuming _id
is the merge key.
use test;
db.users.insert({_id: 1, name: 'Mickey'});
db.users.insert({_id: 2, name: 'Minney'});
db.users2.insert({_id: 1, name: 'Donald'});
db.users2.insert({_id: 2, name: 'Daisy'});
db.users2.insert({_id: 3, name: 'Pluto'});
var users2 = db.users2.find();
while (users2.hasNext()) {
var u2 = users2.next();
var u = db.users.findOne({'_id': u2._id});
if (u == null) {
db.users.insert(u2);
}
}
Mickey
and Minnie
will be preserved and only Pluto
will be added to users
.

arun
- 10,685
- 6
- 59
- 81