在mongodb聚合中计算另一个文档中的项目 [英] Count items from another document in mongodb aggregation
本文介绍了在mongodb聚合中计算另一个文档中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个不同的文档
Accounts
[
{_id:1, name:'xyz'},
{_id:2, name:'abc'},
{_id:3, name:'def'},
{_id:4, name:'pqr'},
]
和
Responses
[
{_id:01, accountId:2, questionId: 0001, res: true},
{_id:02, accountId:2, questionId: 0002, res: true},
{_id:03, accountId:1, questionId: 0003, res: false},
{_id:03, accountId:3, questionId: 0002, res: false},
{_id:03, accountId:2, questionId: 0003, res: false},
]
我如何计算单个帐户的 true 和 false 响应数,同时也要保留其原始字段.
How can I count number of true and false responses for an individual account while maintaining its original fields too.
例如.
{
_id: 2,
name: 'abc',
trueResponses: 2,
falseResponses: 1
}
我曾尝试使用$ lookup在字段中加入其他文档,但无法计算不同的响应.
I have tried using $lookup to join the other document in a field but am unable to count different responses.
db.accounts.aggregate([
{
$match: { _id: 2 }
},
{
$lookup:{
from: 'responses',
localField: '_id',
foreignField: 'accountId',
as: 'responses'
}
}
])
推荐答案
有很多方法,
-
$ match
消除不需要的数据 -
$ lookup
加入收藏集 -
$ unwind
解构数组 -
$ group
重建数组,而$ sum
使用$ cond
条件 帮助增加1
$match
eliminate unwanted data$lookup
to join collections$unwind
to deconstruct the array$group
to reconstruct the array and$sum
helps to increase by 1 using$cond
condition
这是脚本
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]
}
}
}
}
])
工作中蒙哥游乐场
Working Mongo playground
这篇关于在mongodb聚合中计算另一个文档中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文