我有一些文档如下
{
_id: 1,
lender_id: 10,
borrower_id: 20,
message: 'Message from lender'
},
{
_id: 2,
lender_id: 20,
borrower_id: 10,
message: 'Response to lender'
}
{
_id: 3,
lender_id: 10,
borrower_id: 30,
message: 'Message to other user'
}
我想在这种特殊情况下获取lender_id字段或borrower_id等于 10 时的文档计数。
我尝试这个:
chats = await Chat.aggregate([
{
$match: { $or: [
{lender_id: 10},
{borrower_id: 10}
]}
},
{
$group: {
_id: null,
differentChats: {$sum: 1}
}
},
])
// Response: [ { _id: null, differentChats: 3 } ] --- must be 2
我如何获得唯一聊天的总数。 谢谢阅读。
我们需要创建一个唯一lender_id
和borrower_id
Set
,如下所示(通过更改顺序(。在最后阶段,我们采用Set
大小。
chats = await Chat.aggregate([
{
$match: {
$or: [ {lender_id: 10}, {borrower_id: 10} ]
}
},
{
$group: {
_id: null,
differentChats: {
$addToSet: {
$cond: [
{ $gt: ["$lender_id", "$borrower_id"]},
[ "$lender_id", "$borrower_id" ],
[ "$borrower_id", "$lender_id" ]
]
}
}
}
},
{
$project: {
differentChats: { $size: "$differentChats" }
}
}
])
蒙戈游乐场