MongoDB - 查询 collection 和相关 collection 并匹配 collection 中的字段(聚合)
MongoDB - Query collection and related collection and match fields in both collections (Aggregation)
我有以下 collections,其中帐户与公司 collection 有关。引用存储为 accountId。
公司
- 名字
- 账户ID
账户
- 电子邮件
现在我想像那样查询两个collection
db.getCollection('Company').aggregate([
{ $lookup: { from: 'Account', localField: 'accountId', foreignField: '_id', as: 'account' }},
{ $unwind: '$account' },
{ $match : { $or: [{ name : /example/, 'account.email' : /example/ }] } }
])
最后它应该 return 查询与公司名称匹配的所有公司以及查询与相关 account.email 匹配的所有公司(即使公司名称根本不匹配).但我的问题是 $match 阻止了这种情况。
因此,例如具有以下数据的公司应该 returned。
- 名称:Example Inc,account.email:mail@mail.com,
- 姓名:示例公司,account.email:公司@corp.com,
- 名称:不同公司,account.email:示例@example.com
我如何调整聚合方法来检索这样的数据?
谢谢!
尝试使用如下所述的正则表达式。因为您正在尝试类似的查询。
db.getCollection('Company').aggregate([
{ $lookup: { from: 'Account', localField: 'accountId', foreignField: '_id', as: 'account' }},
{ $unwind: '$account' },
{ $match : {$or:[{name: {$regex: "example", $options: "i"}}, {"account.email": {$regex:"example", $options: "i"}}]} }
])
我有以下 collections,其中帐户与公司 collection 有关。引用存储为 accountId。
公司
- 名字
- 账户ID
账户
- 电子邮件
现在我想像那样查询两个collection
db.getCollection('Company').aggregate([
{ $lookup: { from: 'Account', localField: 'accountId', foreignField: '_id', as: 'account' }},
{ $unwind: '$account' },
{ $match : { $or: [{ name : /example/, 'account.email' : /example/ }] } }
])
最后它应该 return 查询与公司名称匹配的所有公司以及查询与相关 account.email 匹配的所有公司(即使公司名称根本不匹配).但我的问题是 $match 阻止了这种情况。
因此,例如具有以下数据的公司应该 returned。
- 名称:Example Inc,account.email:mail@mail.com,
- 姓名:示例公司,account.email:公司@corp.com,
- 名称:不同公司,account.email:示例@example.com
我如何调整聚合方法来检索这样的数据? 谢谢!
尝试使用如下所述的正则表达式。因为您正在尝试类似的查询。
db.getCollection('Company').aggregate([
{ $lookup: { from: 'Account', localField: 'accountId', foreignField: '_id', as: 'account' }},
{ $unwind: '$account' },
{ $match : {$or:[{name: {$regex: "example", $options: "i"}}, {"account.email": {$regex:"example", $options: "i"}}]} }
])