MongoDB Aggregation Query to Count

匆匆过客 提交于 2019-12-11 04:28:26

问题


I am using Nodejs and MongoDB with expressjs and mongoose library & How can I get mutual between another user. 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?


回答1:


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


来源:https://stackoverflow.com/questions/54376551/mongodb-aggregation-query-to-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!