[英]How to JOIN two collection by _id with where condition in Mongodb and NodeJS
我有两个 collections 称为用户和订阅,每个订阅都有 user_id,它是用户集合的 _id。 我如何通过 is_account_active = 1 的条件加入这两个 collections。
请检查我正在使用的以下代码:
const users = await User.find({ is_account_active: 1 });
这将使我获得 is_account_active 标志为 1 的所有用户,但与此同时,我还想要订阅详细信息以及各自的用户 ID。
您可以使用例如aggregate
函数。 如果您将 user_id 保留为字符串并且您的 mongo db 版本 >= 4.0,那么您可以将_id
转换为字符串(因为 _id 是 ObjectId 类型):
const users = await User.aggregate([
{
$match: {
is_account_active: 1
}
},
{
$project: {
"_id": {
"$toString": "$_id"
}
}
},
{
$lookup: {
from: 'subscriptions', //collection name
localField: '_id',
foreignKey: 'user_id',
as: 'subscription'. //alias
}
}
]);
但是将 user_id 存储在订阅模式中作为对象 id 是一个更好的主意
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref:'User'
}
那么
const users = await User.aggregate([
{
$match: {
is_account_active: 1
}
},
{
$lookup: {
from: 'subscriptions', //collection name
localField: '_id',
foreignKey: 'user_id',
as: 'subscription'. //alias
}
}
]);
您可以在下方查询。
const users = await User.aggregate([
{
$match: {
your_condition
}
},
{
$lookup: {
from: 'subscriptions', // secondary db
localField: '_id',
foreignKey: 'user_id',
as: 'subscription' // output to be stored
}
}
]);
但是,如果您可以在主集合中使用像user_id这样的新字段,并且可以使用自动增量,现在将自动插入具有新唯一 id 的新数据,并且您可以在其上创建索引,而不是将_id用作外部字段,这应该更好为了更快的查询执行。
我现在正在使用 Mongodb 和 Mathon 的出色答案。 我在评论中没有指向 state 的声誉点:我相信在'as'之后有一个流浪期并且参数 foreignKey 应该是 foreignField - 至少 Mongodd 6.0.3 和 NodeJS 出现错误。 它适用于我的这些更改,如下所示。
const users = await User.aggregate([ { $match: { is_account_active: 1 } }, { $project: { "_id": { "$toString": "$_id" } } }, { $lookup: { from: 'subscriptions', //collection name localField: '_id', foreignField: 'user_id', as: 'subscription' //alias } } ]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.