【问题标题】:How to set primary id of one collection as secondary id of another collection in mongodb?如何在mongodb中将一个集合的主ID设置为另一个集合的辅助ID?
【发布时间】:2019-07-16 15:20:13
【问题描述】:

我正在构建一个博客站点(在前面使用 angular,在后面使用节点和 mongoDB),我想在其中显示与其特定类别相对应的博客。

我有 3 个不同的博客类别。我创建了两个集合:一个用于类别,另一个用于博客。在 blogs 集合中,我想使用一个名为 c_id 的字段,它应该等于类别集合的 id。因此,当我单击特定类别时,它只会显示该类别的博客。

【问题讨论】:

    标签: node.js mongodb mean-stack


    【解决方案1】:

    在您的博客集合架构中,您可以将字段定义为 c_id 或 categoryId,如下所示:

    var BlogSchema = new Schema({
            _id: {
                type: Schema.Types.ObjectId,
                required: true,
                auto: true,
            },
            blogTitle: {
               type: String
            },
            anyField: {
                type: String
            },
            categoryId: {
                type: Schema.Types.ObjectId,
                ref:"categories",              // Name of your category collection
                required: true,
            },
    });
    

    要获取所有博客以及类别名称,您可以尝试如下查询:

    db.collection.aggregate([
        {
           $lookup: {
                from: "categories",             // Name of the foreign collection
                let: { "cId": "$categoryId" },  
                pipeline:[
                    { 
                      $match: { 
                           $expr: { 
                              $eq: ["$_id", "$$cId"] 
                           } 
                      } 
                    },
                    {
                       $project: {
                           categoryName: 1
                       }
                    }  
                ],
               as: "categoryInfo"
           }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2021-08-25
      相关资源
      最近更新 更多