MongoDB: Find the minimum element in array and delete it
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
}
}
})
})
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'] } } } )