【问题标题】:MongoDB Aggregation Query to Count要计数的 MongoDB 聚合查询
【发布时间】:2019-01-28 01:04:37
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

    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՝ 功能将无法工作,请参阅MongoDB Jira task
    • 你好@Anthony Winzlet,我如何查询 mongo 以根据他关注的帐户建议特定用户关注其他用户
    • @byal 请用适当的解释提出一个新问题
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多