要计数的MongoDB聚合查询

要计数的MongoDB聚合查询,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我正在将Nodejs和MongoDB与expressjs和mongoose库一起使用&如何在其他用户之间获得mutual。下面是我使用的模式 const UsersSchema = new mongoose.Schema({ username: { type: String }, email: { type: String }, date_created: { type: Date }, last_modified: {

我正在将NodejsMongoDB与expressjs和mongoose库一起使用&如何在其他用户之间获得mutual。下面是我使用的模式

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

如何查询Mongo?

您可以使用下面的聚合

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

是的,这是正确的攻击,但请注意,如果MongoDB集合被切分,՝$lookup՝功能将不起作用,请参考Hello@Anthony Winzlet,我如何查询mongo以建议特定用户根据其帐户跟随其他用户follow@byal请提出一个新问题并作适当解释