如何匹配属于连接表的列的条件?
For eg:
Consider two collections A and B:
Collection A:
id|name|status
++++++++++++++
1 |Rock|1
2 |Sam |1
3 |Jack|1
Collection B:
id|userId| loc | status
+++++++++++++++++++++++++++++++++++
1| 1 |[11.111,22.321] | -1
2| 1 |[16.22,33.213] | 1
3| 2 |[334.11,242.321]| 1
4| 3 |[1.111,224.321] | 1
我想根据集合B中的状态字段获取所有用户的当前位置,即用户的当前位置在B中的状态为1,之前的位置的状态为-1。
So, the result I want is like:
+++++++++++++++++
id:1, name: Rock, status: 1, userLocTable: [{id:2, userId:1, loc: [16.22,33.213], status: 1}]
我在做的是:
db.collectionA.aggregate([
{
$lookup: {
from: collectionB,
localField: id,
foreignField: userId,
as: userLocTable
}
},
{
$match:{
userLocTable.status: 1
}
}
])
但是我从查找表(B)获取所有行(状态1和-1),而不是只有状态为1的记录。可能是什么问题。任何帮助都值得赞赏。谢谢!
答案 0 :(得分:3)
试试这个,
db.collectionA.aggregate([
{
"$lookup": {
"from": collectionB,
"localField": id,
"foreignField": userId,
"as": userLocTable
}
},
{
"$addFields": {
"userLocTable": {
"$filter": {
"input": "$userLocTable",
"as": "userLoc",
"cond": {
"$eq": [ "$$userLoc.status", "1" ]
}
}
}
}
}
])