【发布时间】:2021-08-25 11:58:54
【问题描述】:
我是 MongoDB 新手,node.js 在 mongo 查找方面需要帮助。我想根据条件加入两个文档。我正在使用猫鼬、节点和快递。在Conversation 模型的聚合中,我想查找另一个模型User。
这是用户1
{
"_id": "0b3bb0bb2d78405fa941dd3e1da9574a",
"status": true,
"fullName": "Irtza",
"mobileNumber": "+9200000000000",
"createdAt": {
"$date": "2021-05-05T11:39:00.875Z"
},
"updatedAt": {
"$date": "2021-06-04T11:10:53.103Z"
},
"__v": 0,
}
这是用户2
{
"_id": "51701df06d084003853cd0837d76606a",
"status": true,
"fullName": "Shehroz Ali",
"mobileNumber": "+10000000000",
"createdAt": {
"$date": "2021-05-06T11:28:48.980Z"
},
"updatedAt": {
"$date": "2021-06-04T12:34:03.676Z"
},
"__v": 0,
}
他们之间有对话
{
"_id": "9a4d221ebbde4ba68b28783232aed28c",
"userIds": ["0b3bb0bb2d78405fa941dd3e1da9574a", "51701df06d084003853cd0837d76606a"],
"type": "private",
"conversationName": "abc",
"createdAt": {
"$date": "2021-06-04T10:46:43.061Z"
},
"updatedAt": {
"$date": "2021-06-04T10:46:43.061Z"
},
"__v": 0
}
因此,基于上述场景,我想查找/加入与其 ID 未传递给对话的用户的对话。
有一个基于userId 的请求userId 我想查找User 模型。同样在我的Conversation 中,我有一个字符串数组"userIds": ["0b3bb0bb2d78405fa941dd3e1da9574a", "51701df06d084003853cd0837d76606a"] 如果userIds.0 与userId 匹配,则使用userIds.1 查找,如果userIds.1 与userId 匹配,则使用userIds.0 查找这是我的代码:
this.aggregate([
{ $match: { userIds: { $all: [userId] } } },
{
$lookup: {
from: 'users',
localField: 'userIds.0',
foreignField: '_id',
as: 'user1',
}
},
{ $unwind: "$user1" },
{
$lookup: {
from: 'users',
localField: 'userIds.1',
foreignField: '_id',
as: 'user2',
}
},
{ $unwind: "$user2" },
{
$lookup: {
from: 'messages',
localField: '_id',
foreignField: 'conversationId',
as: 'messageBody',
}
},
{ "$addFields": {
"messageBody": {
"$arrayElemAt": [ "$messageBody", -1 ]
}
}},
{ $unwind: "$messageBody" },
]);
【问题讨论】:
-
你能添加一个对话和用户文档的例子吗?
-
@NenadMilosavljevic 请立即查看。
-
我发布了我的答案。检查它是否适合您。
标签: node.js database mongodb express mongoose