简体   繁体   English

MongoDB聚合查询计数

[英]MongoDB Aggregation Query to Count

I am using Nodejs and MongoDB with expressjs and mongoose library & How can I get mutual between another user. 我使用的NodeJSMongoDB与expressjs和猫鼬图书馆&我怎样才能获得其他用户之间的相互 Here are the Schema I use. 这是我使用的架构。

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


const FollowSchema = new Schema({
    follower:        { type: Schema.Types.ObjectId, ref: 'User', required: true },
    following:        { type: Schema.Types.ObjectId, ref: 'User', required: true },
    date_created:    { type: Date },
    last_modified:   { type: Date }
});

How do I Query Mongo ? 如何查询Mongo

You can use below aggregation 您可以使用以下汇总

db.users.aggregate([
  { "$match": { "_id": 2 }},
  { "$lookup": {
    "from": "follows",
    "let": { "id": "$_id" },
    "pipeline": [
      { "$facet": {
        "userFollows": [
          { "$match": { "$expr": { "$eq": ["$follower", "$$id"] }}}
        ],
        "myFollows": [
          { "$match": { "$expr": { "$eq": ["$follower", 1] }}}
        ]
      }},
      { "$project": {
        "matchedFollowed": {
          "$setIntersection": ["$userFollows.followed", "$myFollows.followed"]
        }
      }},
      { "$unwind": "$matchedFollowed" }
    ],
    "as": "user"
  }},
  { "$lookup": {
    "from": "follows",
    "let": { "ids": "$user.matchedFollowed" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$follower", "$$ids"] }}}
    ],
    "as": "mutualConnections"
  }}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM