我正在使用 python3、pymongo、mongodb4.4.3
我有兩個收藏:
assignments: user_id,qid
questions: qid,text,category
當我將它們加入一個基于 qid 的查詢時,它看起來像這樣:
aggregate = [
{
'$match': {
'user_id': user_id
}
},
{
'$lookup': {
'from': 'questions',
'localField': 'qid',
'foreignField': 'qid',
'as': 'question'
}
}
]
result = col_assignments.aggregate(aggregate)
而且效果很好。
但現在我需要根據“問題”集合中的“類別”欄位進行過濾。
互聯網說我需要使用帶有$expr的管道而不是本地和外國欄位。所以我做了這樣的查詢:
aggregate = [
{
'$match': {
'user_id': user_id
}
},
{
'$lookup': {
'from': 'questions',
'let': { 'qid': '$qid' },
'pipeline': [{
'$match': {
'$expr': {'$eq': ['$$qid', 'qid']},
'category': current_category
}
}],
'as': 'question'
}
}
]
而且它不起作用,“問題”是空的。
我猜它與語法有關。但我從未在 mongo shell 和 pymongo 中使用過如此復雜的查詢。你能幫我解決這個問題嗎?
uj5u.com熱心網友回復:
如果要根據相應的問題類別過濾掉整個作業項,則不應在聚合階段內定義類別的條件。而是使用另一個單獨的階段。$lookup$match
aggregate = [
{
'$match': {
'user_id': user_id
}
},
{
'$lookup': {
'from': 'questions',
'localField': 'qid',
'foreignField': 'qid',
'as': 'question'
}
},
{
'$match': {
'question.0.category': current_category
}
}
])
如果您只想過濾掉相應的問題類別,只需$按照ray的建議添加 missing: '$expr': {'$eq': ['$$qid', '$qid']}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459379.html
