簡體   English   中英

MongoDB聚合查詢計數

[英]MongoDB Aggregation Query to Count

我使用的NodeJSMongoDB與expressjs和貓鼬圖書館&我怎樣才能獲得其他用戶之間的相互 這是我使用的架構。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM