简体   繁体   English

如何在 Mongodb 和 NodeJS 中通过 _id 和 where 条件加入两个集合

[英]How to JOIN two collection by _id with where condition in Mongodb and NodeJS

I've two collections called user and subscription, every subscription has user_id which is _id of user collection.我有两个 collections 称为用户和订阅,每个订阅都有 user_id,它是用户集合的 _id。 How can I join these two collections by where condition with is_account_active = 1.我如何通过 is_account_active = 1 的条件加入这两个 collections。

Please check the below code which I'm using:请检查我正在使用的以下代码:

const users = await User.find({ is_account_active: 1 });

This will get me all users which have is_account_active flag as 1 but at the same time, I want subscription details also with respective user ids.这将使我获得 is_account_active 标志为 1 的所有用户,但与此同时,我还想要订阅详细信息以及各自的用户 ID。

You can use for example aggregate function.您可以使用例如aggregate函数。 If you keep user_id as string and you have mongo db version >= 4.0 then you can make _id conversion to string (because _id is an ObjectId type):如果您将 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
    }
  }
]);

But it is a better idea to store user_id in Subscription schema as Object id但是将 user_id 存储在订阅模式中作为对象 id 是一个更好的主意

user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref:'User'
}

so then那么

const users = await User.aggregate([
  {
    $match: {
      is_account_active: 1
    }
  },
  {
    $lookup: {
      from: 'subscriptions',     //collection name
      localField: '_id',
      foreignKey: 'user_id',
      as: 'subscription'.        //alias
    }
  }
]);

More about ObjectId 更多关于 ObjectId

More about Aggregate function更多关于聚合函数

You can below query.您可以在下方查询。

const users = await User.aggregate([
  {
    $match: {
      your_condition
    }
  },
  {
    $lookup: {
      from: 'subscriptions', // secondary db
      localField: '_id',
      foreignKey: 'user_id',
      as: 'subscription' // output to be stored
    }
  }
]);

But instead of using _id as a foreign it should be better if you can use a new field like user_id in primary collection and can use auto increment on that which will now automatically insert new data with new unique id, and you can create index on it for faster query execution.但是,如果您可以在主集合中使用像user_id这样的新字段,并且可以使用自动增量,现在将自动插入具有新唯一 id 的新数据,并且您可以在其上创建索引,而不是将_id用作外部字段,这应该更好为了更快的查询执行。

I'm using Mongodb right now with Mathon's excellent answer.我现在正在使用 Mongodb 和 Mathon 的出色答案。 I don't have the reputation points to state this in the comments: I believe there is a stray period after the 'as' and the argument foreignKey should be foreignField - at least Mongodd 6.0.3 is presenting an error with it and NodeJS.我在评论中没有指向 state 的声誉点:我相信在'as'之后有一个流浪期并且参数 foreignKey 应该是 foreignField - 至少 Mongodd 6.0.3 和 NodeJS 出现错误。 It works for me with those changes as shown below.它适用于我的这些更改,如下所示。

 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.

相关问题 如何使用nodejs合并mongodb中的多个集合 - How to merge multiple collection in mongodb using nodejs 如何在 MongoDB 中从单独的集合中获取数据并将其与用户集合连接,而无需相同的公共 id 来链接它们? - How to get data from a separate collection and join it with a user collection without having a same common id to link both of them in MongoDB? 如何将 _id 与嵌套的 _id MongoDB 连接起来 - How to join _id with nested _id MongoDB MongoDB-等同于不存在一个集合的LEFT JOIN - MongoDB - Equivalent of LEFT JOIN where one collection isn't exists 在NodeJS中组合来自MongoDB集合的两个异步结果 - Combining two async results from MongoDB collection in NodeJS Nodejs - 如何在两个条件下找到索引,一个条件是属性存在的地方 - Nodejs - How to find the index with two conditions, one condition being where a property exists 在mongoDB中加入两个集合,并在节点js中提取数据 - Join two collection in mongoDB and extract out data in node js 如何在羽毛应用程序的mongodb中同时使用相同的id删除两个不同集合中的文档 - How to remove document in two different collection using same id at same time in mongodb on feathers application 如何给JavaScript中的MongoDB whereObj添加where条件 - How to add where condition to the MongoDB whereObj in JavaScript MongoDB 和 Mongoose - 来自两个不同集合查询的 ID 不匹配 - MongoDB and Mongoose - id from two different collection queries not matching
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM