I have a document with a structure similar to this
{
"brand": "BMW",
"models": ["320","545"]
}
Models must be unique, and I am using the following query when adding new items,
db.cars.update(
{brand:'BMW'},
{
$addToSet: {
models: '750'
}
},
{upsert:true}
);
That would give
{
"brand": "BMW",
"models": ["320","545","750"]
}
Question:
How can I limit the total number of items 'models' can have? Say I want to keep only the last 3 added models. So if I insert a new model '135' I would end up with
{
"brand": "BMW",
"models": ["545","750","135"]
}
I read about the $slice
modifier however it appears to be only available when using $push
and not $addToSet