通过匹配 Python 从列表中查找特定值
Finding particular value from a list by matching in Python
我对访问列表中的值有一点疑问。
我有一个元素列表
"result":[{"_id": "55b8b9913f32df094c7ba922", "Total": "450"},
{"_id": "55b8a2083f32df1030b9ef16", "Total": "400"}]
在这里,我们基本上是通过 list[0]
或类似的基于编号的方式从列表中获取值。列表元素。
我想知道我们是否可以通过将列表与 _id
匹配来仅从列表中获取特定值。因为如果数据库很大,则很难通过 list[]
获取值
我的实际代码是:
id = self.body['_id']
test = yield db.Result.aggregate(
[
{ '$group': { '_id' : "$StudentId",
'Total': {'$max': "$Total"}}
}
]
)
list = test.get('result')
print(list)
我只想得到所提供的总数id
。
首先使用 $match
来获取您想要的文件。
id = self.body['_id']
test = yield db.Result.aggregate(
[
{ '$match': { '_id': id } },
{ '$group': { '_id' : "$StudentId",
'Total': {'$max': "$Total"}}
}
]
)
list = test.get('result')
print(list)
并且要匹配多个值,使用$in
,声明一个数组
listOfIds = [id1,id2,id3]
管道变化:
{ '$match': { '_id': { '$in': listOfIds } },
正如我之前所说:
Your "Total" field contains a "string". If you don't change that to be numeric you will get unexpected results. Strings sort differently to numbers. i.e "8" is greater that "100".
所以你真的应该在你的数据中改变它。
我对访问列表中的值有一点疑问。 我有一个元素列表
"result":[{"_id": "55b8b9913f32df094c7ba922", "Total": "450"},
{"_id": "55b8a2083f32df1030b9ef16", "Total": "400"}]
在这里,我们基本上是通过 list[0]
或类似的基于编号的方式从列表中获取值。列表元素。
我想知道我们是否可以通过将列表与 _id
匹配来仅从列表中获取特定值。因为如果数据库很大,则很难通过 list[]
我的实际代码是:
id = self.body['_id']
test = yield db.Result.aggregate(
[
{ '$group': { '_id' : "$StudentId",
'Total': {'$max': "$Total"}}
}
]
)
list = test.get('result')
print(list)
我只想得到所提供的总数id
。
首先使用 $match
来获取您想要的文件。
id = self.body['_id']
test = yield db.Result.aggregate(
[
{ '$match': { '_id': id } },
{ '$group': { '_id' : "$StudentId",
'Total': {'$max': "$Total"}}
}
]
)
list = test.get('result')
print(list)
并且要匹配多个值,使用$in
,声明一个数组
listOfIds = [id1,id2,id3]
管道变化:
{ '$match': { '_id': { '$in': listOfIds } },
正如我之前所说:
Your "Total" field contains a "string". If you don't change that to be numeric you will get unexpected results. Strings sort differently to numbers. i.e "8" is greater that "100".
所以你真的应该在你的数据中改变它。