MongoDB:找到数组中的最小元素并将其删除 [英] MongoDB: Find the minimum element in array and delete it
问题描述
我在MongoDB中有一个文档,其中一个看起来像这样:
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"
}
]
}
似乎应该在这里使用findAndModify
函数,但是我不能再继续了.
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?
我正在使用MongoDB和Pymongo驱动程序.
I'm using MongoDB and Pymongo driver.
推荐答案
如果您不局限于将查询放在一个步骤中,则可以尝试:
If you are not restricted to having the query be in one single step, you could try:
步骤1)将聚合函数与$ unwind和$ group运算符配合使用,以查找每个文档的最小项目
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" } } } ] )
第2步)遍历结果并从数组中拉出元素
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'] } } } )
这篇关于MongoDB:找到数组中的最小元素并将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!