node.js - MongoDB搜索多个集合
问题描述
基本上我正在搜索消息。我有 2 个收藏:
- 用户
- 留言
用户:
[
{
"_id": "Xuibgsadbgsi35Gsdf",
"fullName": "User A"
},
{
"_id": "Afstg34tg4536gh",
"fullName": "User B"
},
{
"_id": "KHJDFhfs7dfgsvdfwsef",
"fullName": "User C"
}
]
留言:
[
{
"_id": "YONgsa793423bD",
"groupId": "Phsdfyg92345sgb7651",
"senderId": "Xuibgsadbgsi35Gsdf",
"message": "Hello there!"
},
{
"_id": "sdgDFGbaofh135df",
"groupId": "Phsdfyg92345sgb7651",
"senderId": "KHJDFhfs7dfgsvdfwsef",
"message": "Hello @Xuibgsadbgsi35Gsdf"
},
{
"_id": "sdgDFGbaofh135df",
"groupId": "Phsdfyg92345sgb7651",
"senderId": "KHJDFhfs7dfgsvdfwsef",
"message": "Hello"
}
]
现在我想在这里搜索:User A
,所以我应该得到那些User A
以任何方式涉及的消息,要么他是发件人,要么他在某些消息文本中被提及。
如何查询这种情况?
解决方案
你可以这样做
db.users.aggregate([
{
$match: {
fullName: "User A"
}
},
{
"$lookup": {
"from": "messages",
let: {
id: "$_id" //This is what you need to match in the messages collection, kind of variable
},
"pipeline": [
{
$match: {
$or: [
{
$expr: { //Matching in sender id
$eq: [
"$senderId",
"$$id"
]
}
},
{
$expr: {
"$regexMatch": { //matching in messages
"input": "$message",
"regex": "$$id",
}
}
}
]
}
}
],
"as": "senders"
}
},
{
$match: {
$expr: {
"$gt": [//Filtering only the matched results
{
"$size": "$senders"
},
0
]
}
}
}
])
要添加过滤,您可以match
在查找之前添加一个阶段,如下所示
{
$match: {
fullName: "User A"
}
}
注意,mongo 是区分大小写的数据库。更新样本
推荐阅读
- phabricator - 将 Phabricator(Maniphest)任务字段的查看访问权限限制为仅特定用户组?
- sql - 如何修复 SQL Server 并转换和替换查询?
- python-3.x - 如何查看动态生成的纸浆方程
- python - iPython 在 OS X 上的 Visual Studio Code 中自动启动
- delphi - Delphi TTimer 在 Win 10 中提供不寻常的结果
- ios - 哪种数据模型最适合存储类似 instagram 的数据?
- postgresql-9.2 - Postgresql 未对用户进行身份验证
- swift - 如何使用继承创建节点?
- python - 使用公共数据源同步的 QListWidget
- php - 在 WooCommerce 中隐藏缺货的相关产品