将数组元素与文档值和过滤器匹配

时间:2017-07-19 04:12:55

标签: mongodb mongodb-query aggregation-framework

我有一组具有以下结构的文档: enter image description here

联盟和条目都是我展开的数组(),但是我需要找到文件的属性“nick”在“playerOrTeamName”上显示的位置。

db.getCollection('summoners').aggregate([
    {"$skip": 0},
    {"$limit": 2},
    {'$unwind': '$leagues'},
    {'$unwind': '$leagues.entries'},
    {'$match': {'leagues.entries.playerOrTeamName': '$nick'}},
],{

allowDiskUse:真  })

为什么“匹配”部分会产生0结果?我可以确保玩家的昵称总是出现在条目阵列上。

PS:limit = 2用于简单sakes

1 个答案:

答案 0 :(得分:1)

失败的原因是因为"$nick"意味着是另一个字段的值,但$match基本上只是一个常规的MongoDB查询"没有"使用变量"的概念从现有的字段值开始,以便匹配"条件。

因此,您应该使用"aggregation logical operators"来使用$redact管道阶段,或者使用"过滤"数组内容直接使用$filter

db.getCollection('summoners').aggregate([
    {"$skip": 0},
    {"$limit": 2},
    {'$unwind': '$leagues'},
    {'$unwind': '$leagues.entries'},
    {'$redact': {
      '$cond': {
        'if': { '$eq': [ '$leagues.entries.playerOrTeamName', '$nick' ] }
        'then': '$$KEEP',
        'else': '$$PRUNE'
      }
    }
])

执行"逻辑"对字段值进行比较,并根据"$$KEEP"的结果确定条件为true"$$PRUNE"的{​​{1}}。

或直接在阵列上保持原封:

false

通过将$filter应用于内部db.getCollection('summoners').aggregate([ { "$skip": 0 }, { "$limit": 2 }, { "$addFields": { "leagues": { "$filter": { "input": { "$map": { "input": "$leagues", "as": "l", "in": { "entries": { "$filter": { "input": "$$l.entries", "as": "e", "cond": { "$eq": [ "$$e.playerOrTeamName", "$nick" ] } } }, "name": "$$l.name", "queque": "$$l.queque", "tier": "$$l.tier" } } }, "as": "l", "cond": { "$gt": [ { "$size": "$$l.entries" }, 0 ] } } } }} ]) 以进行字段比较,以及"外部"数组不再在"entries"中留下任何结果,该数组也将被删除。