Try the following in a shell, it will iterate over each item in the collection and try to match each document based on the identifier.
Let's say we have 2 collections of db.col1
and db.col2
:
> db.col1.find() { "_id" : 1, "item" : 1 } { "_id" : 2, "item" : 2 } { "_id" : 3, "item" : 3 } { "_id" : 4, "item" : 4 } > db.col2.find() { "_id" : 1, "item" : 1 } { "_id" : 2, "item" : 2 } { "_id" : 3, "item" : 3 } { "_id" : 4, "item" : 4 }
Then we can create a javascript function to compare the two collections.
function compareCollection(col1, col2){ if(col1.count() !== col2.count()){ return false; } var same = true; var compared = col1.find().forEach(function(doc1){ var doc2 = col2.findOne({_id: doc1._id}); same = same && JSON.stringify(doc1)==JSON.stringify(doc2); }); return same; }
Then the call looks like this:
> compareCollection(db.col1, db.col2) true
If we then have the 3rd db.col3
collection
> db.col3.find() { "_id" : 1, "item" : 1 }
And compare this
> compareCollection(db.col1, db.col3) false
we will get the expected result.
If we also have a fourth set that has the relevant documents, but different data db.col4
> db.col4.find() { "_id" : 1, "item" : 10 } { "_id" : 2, "item" : 2 } { "_id" : 3, "item" : 3 } { "_id" : 4, "item" : 4 }
This will also return false
> compareCollection(db.col1, db.col4) false