MongoDB聚合,Mongodb查询

拜尔

我将Nodejs和MongoDB与expressjs和mongoose库一起使用,创建了一个具有用户文章评论架构Blog API以下是我使用的架构。

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 } 
});
阿什

您可以使用$lookupmongodb 3.6及更高版本中的以下聚合

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"] }
  }}
])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章