我有关于问题和答案以及回答问题的用户的数据
数据
{
text: 'question one',
users: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
answers: [
{ text: 'answer one', users: [2, 3, 6, 7] },
{ text: 'answer two', users: [1, 4, 3, 8, 10] },
{ text: 'answer three', users: [1, 5, 7, 9] },
{ text: 'answer four', users: [2, 4, 6, 8, 10] }
]
}
,我有一个用户列表:[2、3、8、9、10]。我想得到的是根据问题过滤用户数组,并根据我拥有的用户数组来回答每个问题,这样数据就应该像这样
{
text: 'question one',
users: [2, 3, 8, 9, 10],
answers: [
{ text: 'answer one', users: [2, 3] },
{ text: 'answer two', users: [3, 8, 10] },
{ text: 'answer three', users: [9] },
{ text: 'answer four', users: [2, 8, 10] },
]
}
我如何在mongodb中获得它?
如果我可以用长度替换过滤数组
{
text: 'question one',
users: 4,
answers: [
{ text: 'answer one', users: 2 },
{ text: 'answer two', users: 3 },
{ text: 'answer three', users: 1 },
{ text: 'answer four', users: 3 },
]
}
我找到了一种过滤有问题的用户的解决方案,但是我不能在每个答案中过滤用户
db.getCollection('questions').aggregate([{
$project: {
users: {
$setIntersection: [ [ObjectId("5d1ae16452ca833de98e9a79")],'$users']
},
// cannot filter these users
'answers.users': {
$setIntersection: [ [ObjectId("5d1ae16452ca833de98e9a79")], '$answers.users']
}
},
}])