mongo $ne
是否可以在$project
中返回值而不是true
或false
?
文档:
{
"_id" : ObjectId("5d1449db6f934a2926c175d1"),
"clients" : [
"82",
"85"
],
"roomId" : 1,
"message" : [
{
"time" : ISODate("2019-06-27T04:44:49.528Z"),
"status" : "SEND",
"text" : "Ellorad",
"sender" : "82",
"reciever" : "82",
"_id" : ObjectId("5d1449db6f934a2926c175d2")
},
{
"time" : ISODate("2019-06-27T04:44:49.528Z"),
"status" : "SEND",
"text" : "helas veronaaah",
"sender" : "82",
"reciever" : "85",
"_id" : ObjectId("5d1449ff6f934a2926c175d3")
}
]
}
我尝试过的:
Chat.aggregate([
{ $match: { clients: 82 } },
{
$project: {
_id: '$roomId',
receiver: { $ne: ['$clients', 82] },
message: { $slice: ['$message', -1] }
}
}
])
结果:
{
"message": [
{
"_id": 1,
"receiver": true
"message": [
{
"time": "2019-06-27T04:44:49.528Z",
"status": "SEND",
"text": "helas veronaaah",
"sender": "82",
"reciever": "85",
"_id": "5d1449ff6f934a2926c175d3"
}
]
}
]
}
因此接收方在这里只是返回true或false,考虑到其$ne
是正确的,但是我想要的结果是,此处的接收方为'85'而不是true
或{{1 }}
答案 0 :(得分:0)
为什么不呢?
1)unwind
客户数组,和
2)在下一阶段使用$match
排除不需要的值(在这种情况下为82)
3)使用$project
阶段获得所需的结果,clients
将具有所需的receiver
。
尝试一下:
Chat.aggregate([
{ $match: { clients: 82 } },
{
$unwind : "clients"
},
{
$match : {
clients : {$ne : 82}
}
},
{
$project : {
_id: '$roomId',
receiver: "$clients",
message: { $slice: ['$message', -1] }
}
}
])