【问题标题】:MongoDB (Mongoose) join query with paginationMongoDB (Mongoose) 使用分页连接查询
【发布时间】:2021-12-26 00:47:35
【问题描述】:

我有两个 mongoDB 模型

var CompanySchema = new Schema({
    company_name: {
        type: String,
        required: true
    })
    application.accountDB.model('companies', CompanySchema)

var UserSchema = new Schema({
        customer_email: {
        type: String,
        required: false
       },
        company_id: {
        type: String,
        required: false,
        ref: 'companies'
       }
    application.accountDB.model('users', UserSchema)

我正在尝试对公司进行分页并从用户表中获取电子邮件,但是下面的查询导致对用户进行分页并填充公司,我想要相反的方式。

 users.find({},{limit:10, page:0 },{populate : [{path:"company",model : application.accountDB.model('companies')}]})

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    从您的解释看来,Companies 是您想要关注的主要集合,并且能够查看与该公司关联的 Users 的相关信息?

    基于该用例,最好的方法是在 Companies 架构上进行操作,然后在对 Companies 进行分页后加入 Users 集合。

    另外,MongoDB Aggregation 非常适合这种类型的查询,我建议使用它。我提供的示例使用 Mongo 聚合来检索 Companies 的分页列表及其关联的 Users

    const paginatedCompanies = await Companies.aggregate([
        { $match: { ... } },   // Use this to filter the companies if required
        { $sort: { "<field>": 1 } },   // Replace <field> with the name of whatever field you want to sort on
        { $skip: <skip> },   // Replace <skip> with the number of records you want to skip over 
        { $limit: <limit> },   // Replace <limit> with the page size you want
        { $lookup: {
            from: "Users",
            localField: "_id",
            foreignField: "company_id",
            as: "users"
        } }
    ]);
    

    应该输出如下内容:

    [
        {
            _id: "companyId",
            company_name: "Company Name",
            users: [
                {
                    _id: "userId",
                    customer_email: "email",
                    company_id: "companyId"
                },
                ...
            ]
        },
        ...
    ]
    

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 2014-10-10
      • 2018-10-25
      • 2021-05-12
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多