Có nhiều cách,
-
$matchloại bỏ dữ liệu không mong muốn -
$lookuptham gia các bộ sưu tập -
$unwindđể giải cấu trúc mảng -
$groupđể tạo lại mảng và$sumgiúp tăng 1 khi sử dụng$condtình trạng
Đây là tập lệnh
db.Accounts.aggregate([
{ $match: { _id: 2 } },
{
$lookup: {
from: "Responses",
localField: "_id",
foreignField: "accountId",
as: "responses"
}
},
{
$unwind: "$responses"
},
{
$group: {
_id: "$_id",
name: { $first: "$name" },
trueResponses: {
$sum: {
$cond: [{ $eq: [ "$responses.res", true]},1,0]
}
},
falseResponses: {
$sum: {
$cond: [{ $eq: [ "$responses.res", false]},1,0]
}
}
}
}
])
Làm việc sân chơi Mongo