MongoDB: find unique documents between a date range in a collection

I am not sure how to complete this task.

Here is the structure of the document

name: date_created: val: 

I need to find unique documents created between January 2011 and October 2011

I know that I can find out the number of documents between two date ranges as

 db.collection.find({'date_created': {'$gte': '2011-01-01', '$lt': '2011-10-30'}}); 

and i can know how

 db.runCommand({'distinct': 'collection', 'key': 'name'}) 

Problem

The problem is that inside the collection there are duplicate documents that need to be deleted.

How can I answer this question?

 find out unique documents created between January 2011 and October 2011 where uniqueness is based on 'name' key 

UPDATE

@Sergio ansewer is excellent, after executing the request, I got the following result, and you can see that output number < input number , which means that duplicates were deleted

 { "result" : "temp_collection", "timeMillis" : 1509717, "counts" : { "input" : 592364, "emit" : 592364, "output" : 380827 }, "ok" : 1 } 
+4
source share
2 answers

It seems that it can be solved with map-reduce. Something like this should help.

 var map = function() { emit(this.name, this); } var reduce = function(key, vals) { // vals contains all documents for this key (name). Just pick one. return vals[0]; } db.runCommand({ mapreduce: 'collection', map: map, reduce: reduce, query: {'date_created': {'$gte': '2011-01-01', '$lt': '2011-10-30'}}, out: 'temp_collection' }); 

After this command returns, you should have your unique documents in temp_collection .

+6
source

With the addition of an aggregation structure in MongoDB 2.1, you can also:

 db.collection.aggregate([ {$match: {'date_created': {'$gte': '2011-01-01', '$lt': '2011-10-30'}}}, {$sort: {name: 1}}, {$group: { _id: '$name', val: {$first: '$val'} }} ]) 
+2
source

All Articles