Reputation: 540
I have documents with my internal id field inside of each document and date when this document was added. There could be number of documents with the same id (differents versions of the same document), but dates will always be different for those documents. I want in some query, to bring only one document from all versions of the same document (with same id field) that was relevant to specified date, and I want to display them with paging (50 rows in the page). So, is there any chance to do this in MongoDB (operations - query documents by some field, group them by id field, sort by date field and take only first, and all this should be with paging.) ?
Please see example :Those are documents, some of them different documents,like documents A,B and C, and some are versions of the same documents, like _id: 1, 2 and 3 are all version of the same document A
Document A { _id : 1, "id" : "A", "author" : "value", "date" : "2015-11-05" }
Document A { _id : 2, "id" : "A", "author" : "value", "date" : "2015-11-06" }
Document A { _id : 3, "id" : "A", "author" : "value", "date" : "2015-11-07" }
Document B { _id : 4, "id" : "B", "author" : "value", "date" : "2015-11-06" }
Document B { _id : 5, "id" : "B", "author" : "value", "date" : "2015-11-07" }
Document C { _id : 6, "id" : "C", "author" : "value", "date" : "2015-11-07" }
And I want to query all documents that has "value" in the "author" field. And from those documents to bring only one document of each with latest date for the specified date, for example 2015-11-08. So, I expect the result to be : _id : 3, _id : 5, _id : 6 And also paging , for example 10 documents in each page.
Thanks !!!!!
Upvotes: 1
Views: 386
Reputation: 20703
_id
. There is a unique index on _id
by default._id
field which includes the date: {
"_id":{
docId: yourFormerIdValue,
date: new ISODate()
}
// other fields
}
To get the version valid at a specified date, the query becomes rather easy:
db.yourColl.find({
"_id":{
"docId": idToFind,
// get only the version valid up to a specific date...
"date":{ "$lte": someISODate }
}
})
// ...sort the results descending...
.sort("_id.date":-1)
// ...and get only the first and therefor newest entry
.limit(1)
Upvotes: 0