MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Zu zählende MongoDB-Aggregationsabfrage

Sie können die folgende Aggregation verwenden

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