【问题标题】:MongoDB Aggregation, Mongodb QueryMongoDB聚合,MongoDB查询
【发布时间】:2019-06-18 13:17:36
【问题描述】:

我正在使用 Nodejs 和 MongoDB 以及 expressjs 和 mongoose 库,创建一个具有 用户Blog API文章 & cmets 架构。以下是我使用的架构。

const UsersSchema = new mongoose.Schema({
    username:        { type: String },
    email:           { type: String },
    date_created:    { type: Date },
    last_modified:   { type: Date }
});    




const ArticleSchema = new mongoose.Schema({
    id:              { type: String, required: true },
    text:            { type: String, required: true }, 
    posted_by:       { type: Schema.Types.ObjectId, ref: 'User', required: true },
    images:          [{ type: String }],
    date_created:    { type: Date },
    last_modified:   { type: Date }
});




const CommentSchema = new mongoose.Schema({
    id:             { type: String, required: true },
    commented_by:   { type: Schema.Types.ObjectId, ref: 'User', required: true },
    article:        { type: Schema.Types.ObjectId, ref: 'Article' },
    text:           { type: String, required: true },
    date_created:   { type: Date },
    last_modified:  { type: Date } 
});

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用以下来自 mongodb 3.6 及更高版本的$lookup 聚合

    Article.aggregate([
      { "$match": { "posted_by": mongoose.Types.ObjectId(id) } },
      { "$lookup": {
        "from": Comment.collection.name,
        "let": { "id": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$article", "$$id" ] } } }
        ],
        "as": "comments"
      }},
      { "$addFields": {
        "comments_no": { "$size": "$comments" },
        "hasCommented": { "$in": [mongoose.Types.ObjectId(id), "$comments.commented_by"] }
      }}
    ])
    

    【讨论】:

    • 好的,如果您想获取所有用户的数据,请删除$match 阶段。 它没有返回确切的评论数量它不应该发生
    • 是的,它正在工作,但是当 MongoDB Replicaset 启用时。如果启用,您将无法使用某些聚合功能,包括$lookup,所以要小心。
    • @GorKotikyan $lookup 的限制(在 MongoDB 4.0 中)是 from 集合必须是非分片的并且在同一个数据库中——你仍然可以在一个数据库中使用 $lookup 命令副本集或分片环境。如需扩展支持,您可以在 MongoDB 问题中观看/支持相关功能请求:SERVER-29159: Add $lookup support for sharded collections
    • 你好,@AnthonyWinzlet 你能帮我解决这个问题吗? stackoverflow.com/q/54376551/9159002
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2021-09-03
    • 2021-06-02
    相关资源
    最近更新 更多