Is it possible through any mongoDb feature ?
Hi Yuvraj,
Depending on your use case, you could try modifying your schema to group ExternalId
values together in a single document. Each document would then have an array field to contain max of 4 records. For example:
{'ExternalId': 12,
'records': [ { value:1, date: ISODate(" ") }, { value:2, date: ISODate(" ") }, ...
] }
{'ExternalId': 13,
'records': [ { value:1, date: ISODate(" ") }, ...
] }
Then you can limit the number of elements in the array after an update by utilising $each, $sort and $slice. For example:
db.collection.update(
{ externalId: 12 },
{ $push: {
records: {
$each:[ {value: 3, date: new Date() } ],
$sort:{ date : 1 },
$slice: -4
}
}
}
)
The $slice
modifier will keep the last 4 elements of the ordered records
array.
Regards,
Wan.