如何在同一查询中检索用户的关注者和我已经在mongodb中关注的用户

时间:2018-08-16 04:20:21

标签: database mongodb lookup

我在此集合中使用了mongodb:用户和关注。用户集合具有用户,关注者具有关注者映射。

尝试运行此查询,但仅获得用户的关注者以及我的关注对象:

users = User.collection.aggregate([{
    "$lookup": {
      from: "follows",
      localField: "_id",
      foreignField: "followable_id",
      as: "follow"
    }
  },
  {
    "$match": {
      "follow.followable_type": "User",
      "follow.user_id": BSON::ObjectId.from_string(userid)
    }
  },
  {
    "$group": {
      _id: "$follow.followable_id",
      count: {
        "$sum": 1
      },
      data: {
        "$addToSet": "$$ROOT"
      },
    }
  },
  {
    "$project": {
      _id: 1,
      data: 1,
      count: 1,
      follow: {
        '$cond': {
          'if': {
            '$eq': ["$count", 2]
          },
          then: true,
          else: false
        }
      }
    }
  },
  {
    "$skip": 0 * 10
  },
  {
    "$limit": 10
  }
])

  users.each do |user|
    puts "#{user['data'].first['name']}: #{user['follow']}: #{user['count']}"
  end

如何在同一查询中返回我关注的用户?

输出:

  Diego_Lukmiller: false: 1
  Marianno: false: 1
  kah: false: 1
  Fausto Torres: false: 1

1 个答案:

答案 0 :(得分:0)

我通过三个步骤(用红宝石/蒙古包编写)解决/修复了该问题:

  //get users the user X follows
  users = Follow.collection.aggregate([
    { "$match": { "followable_id": BSON::ObjectId.from_string(userid) } },
    { "$lookup": { from: "users", localField: "user_id", foreignField: "_id", as: "user" } },
    { "$unwind": "$user" },
    { "$sort": {"created_at":-1} },
    { "$skip": page * 10 },
    { "$limit": 10 },
    { "$group":{ _id: "$followable_id", data: {"$addToSet": "$user._id"} } }
  ])
  userids=users.blank? ? [] : users.first['data'].to_a

  //get users I follow
  f=Follow.collection.aggregate([
    {"$match":{user_id: BSON::ObjectId.from_string(meid), followable_id: {"$in":userids}}},
    {"$group":{ _id: nil, data: {"$addToSet": "$followable_id"}}}
  ])

  //make intersection
  users = User.collection.aggregate([
    { "$lookup": { from: "follows", localField: "_id", foreignField: "user_id", as: "follow" } },
    { "$unwind": "$follow" },
    { "$match": { "follow.followable_type": "User","follow.followable_id": BSON::ObjectId.from_string(userid) } },
    { "$group":{ _id: "$_id", data:{"$addToSet": "$$ROOT"}} },
    { "$unwind": "$data" },
    { "$project": {
        _id: 1,data: 1,count: 1,
        follow: {
          '$cond': {
            "if": { '$in': [ "$_id", f.first['data'] ]  }, "then": true,
            "else": false
          }
        }
      }
    },
    { "$skip": page * 10 },
    { "$limit": 10 }
  ])

输出:

name: Fausto Torres; Do I follow too? false; Counter that's make the magic: 1
name: kah; Do I follow too? false; Counter that's make the magic: 1
name: Marianno; Do I follow too? true; Counter that's make the magic: 2
name: Diego_Lukmiller; Do I follow too? true; Counter that's make the magic: 2

查询执行速度非常快,看起来很简单。 有没有办法/如何在单个查询中解决?!