MongoDB: Find the minimum element in array and delete it


Question

I have a documents in MongoDB, one of them looks like this:

{
"_id" : 100,
"name" : "Something",
"items" : [
    {
        "item" : 47,
        "color" : "red"
    },
    {
        "item" : 44,
        "color" : "green"
    },
    {
        "item" : 39,
        "color" : "blue"
    }
]
}

In every document I need to find the minimum item and delete it. So it should be like this:

{
"_id" : 100,
"name" : "Something",
"items" : [
    {
        "item" : 47,
        "color" : "red"
    },
    {
        "item" : 44,
        "color" : "green"
    }
]
}

It looks like findAndModify function should be used here but I can't go any further.

How to find the minimum element in array and delete it?

I'm using MongoDB and Pymongo driver.

1
12
11/11/2012 8:57:43 PM

Accepted Answer

If you are not restricted to having the query be in one single step, you could try:

step 1) use the aggregate function with the $unwind and $group operators to find the minimum item for each document

myresults = db.megas.aggregate( [ { "$unwind": "$items" },  
    {"$group": { '_id':'$_id' , 'minitem': {'$min': "$items.item" } } } ] )

step 2) the loop through the results and $pull the element from the array

for result in myresults['result']:
    db.megas.update( { '_id': result['_id'] }, 
        { '$pull': { 'items': { 'item': result['minitem'] } } } )
18
11/12/2012 6:14:04 PM

Please find my solution written in plain javascript. It should work straight through MongoDb shell

cursor = db.students.aggregate(
[{ "$unwind": "$items" }, 
 { "$match": { "items.color": "green"}},
 { "$group": {'_id': '$_id', 'minitem': {
                '$min': "$items.item"
            }
        }
    }

]);

cursor.forEach(
function(coll) {
    db.students.update({
        '_id': coll._id
    }, {
        '$pull': {
            'items': {
                'item': coll.minitem
            }
        }
    })
})

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon