我有一个Collection ,看起来像这样:
{
"_id" : ObjectId("65977bef1ccf990fe33ffc0d"),
"email" : "yww24@gmail.com",
}
{
"_id" : ObjectId("65977bef1ccf990fe33ffc0f"),
"email" : "iqiyz@gmail.com",
"phone" : "8887774455"
}
{
"_id" : ObjectId("65977bef1ccf990fe33ffc10"),
"email" : "46d9s@gmail.com"
}
{
"_id" : ObjectId("65977bef1ccf990fe33ffc0e"),
"phone" : "6669997744"
}
我正在try 将其汇总,结果如下所示:
{
'yww24@gmail.com': 1, // 1 can be any value (e.g. true, "yes", etc)
'iqiyz@gmail.com': 1,
'46d9s@gmail.com': 1,
'8887774455': 1,
'6669997744': 1
}
一旦从数据库中获取了数据集,我就可以使用lodash
库来实现这一点.我只是希望使用MongoDB来做这件事(我的假设是它的资源密集度会更低,但我可能错了).
所以我现在是这样做的:
Coll.aggregate([
{
$match: {}
},
{
$project: {
_id: false,
email: true,
phone: true
}
}
])
.then(logs => {
console.log(logs);
const result = {emails: _.invertBy(logs, 'email'), phones: _.invertBy(logs, 'phone')}
delete result.emails.undefined;
delete result.phones.undefined;
console.log({...result.emails, ...result.phones});
})
是的,结果几乎就是我想要的,但是,再说一次,有没有办法在数据库端做到这一点:
{
'yww24@gmail.com': [ '0' ],
'iqiyz@gmail.com': [ '1' ],
'46d9s@gmail.com': [ '2' ],
'8887774455': [ '1' ],
'6669997744': [ '3' ]
}