[英]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.