Restrict number of record in mongoDb collection.

10 views
Skip to first unread message

yuvraj patel

unread,
Apr 13, 2016, 8:20:06 AM4/13/16
to mongodb-user
Hello all,

I have mongoDb collection and it contains the records like below --

{'ExternalId': 12, . ...  .... .... }
{'ExternalId': 12, . ...  .... .... }
{'ExternalId': 12, . ...  .... .... }
{'ExternalId': 12, . ...  .... .... }
{'ExternalId': 13, . ...  .... .... }
{'ExternalId': 13, . ...  .... .... }
{'ExternalId': 13, . ...  .... .... }
{'ExternalId': 13, . ...  .... .... }
{'ExternalId': 14, . ...  .... .... }
{'ExternalId': 14, . ...  .... .... }
{'ExternalId': 14, . ...  .... .... }
{'ExternalId': 15, . ...  .... .... }
....
...

My requirement is that this collection should have at max 4 records for each 'ExternalId'.  If collection has 4 records for 'ExternalId' 4 and i called insert operation for new record of 'ExternalId' 4 then i need to delete that forth record for 'ExternalId' 4 and keep the new one in Collection.

Is it possible through any mongoDb feature ?
If i have to do it programatically what is the best way i should pick?

Thanks in advance

Wan Bachtiar

unread,
Apr 14, 2016, 11:55:39 PM4/14/16
to mongodb-user

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.

Reply all
Reply to author
Forward
0 new messages