如何使用聚合mongodb从2个集合中获取链接数据

yqhsw0fo  于 2021-10-10  发布在  Java
关注(0)|答案(2)|浏览(429)

我是新来的mongodb,我有两个系列: UserVideo 具有以下结构。当用户喜欢视频时,视频 _id 将添加到 liked_videos 关于用户集合。 liked_videos 是_id的数组
视频采集

{
    _id
    mp4_url,
    liked_count
}

用户集合

{
    _id,
    username,
    password,
    liked_videos: [ // videos _id array ]
}

如何查询以获取用户喜欢的视频?像下面这样?

[
    {
    _id: 1
    mp4_url,
    liked_count
    },
    {
    _id: 2
    mp4_url,
    liked_count
    },
    ...
]

非常感谢。

bmvo0sr5

bmvo0sr51#

你需要使用 $lookup 加入集合和 $size 获取数组大小的步骤

db.video.aggregate([
  {
    "$lookup": {
      "from": "user",
      "localField": "_id",
      "foreignField": "liked_videos",
      "as": "join_video"
    }
  },
  {
    "$project": {
      liked_count: {
        $size: "$join_video"
      }
    }
  }
])

工作旺哥Playground

sqougxex

sqougxex2#

这样试试

db={
  "video": [
    {
      "_id": 1,
      "mp4_url": "url1",
      "liked_count": 2,
      "quantity": 2
    },
    {
      "_id": 2,
      "mp4_url": "url2",
      "liked_count": 3,
      "quantity": 1
    },
    {
      "_id": 3,
      "mp4_url": "url2",
      "liked_count": 3,
      "quantity": 4
    }
  ],
  "User": [
    {
      "_id": 1,
      "username": "almonds",
      "password": "pwd",
      "Likedvideos": [
        "aaa",
        "ffff"
      ]
    },
    {
      "_id": 2,
      "username": "almonds",
      "password": "pwd",
      "Likedvideos": [
        "qqq",
        "bbbb"
      ]
    },
    {
      "_id": 3,
      "username": "almonds",
      "password": "pwd",
      "Likedvideos": [
        "ccc",
        "ffff"
      ]
    },
    {
      "_id": 4,
      "username": "almonds",
      "password": "pwd",
      "Likedvideos": [
        "bbbb",
        "ffff"
      ]
    },
    {
      "_id": 5,
      "username": "almonds",
      "password": "pwd",
      "Likedvideos": [
        "qqq",
        "ffff"
      ]
    },
    {
      "_id": 6
    }
  ]
}

查询:

db.video.aggregate([
  {
    $match: {
      _id: 1
    }
  },
  {
    "$lookup": {
      "from": "User",
      "localField": "_id",
      "foreignField": "_id",
      "as": "data"
    },

  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$data",
          "$$ROOT"
        ]
      }
    }
  },
  {
    $project: {
      data: 0
    }
  }
])

输出:

[
  {
    "Likedvideos": [
      "aaa",
      "ffff"
    ],
    "_id": 1,
    "liked_count": 2,
    "mp4_url": "url1",
    "password": "pwd",
    "quantity": 2,
    "username": "almonds"
  }
]

mongoplayground

相关问题