简体   繁体   中英

How to get linked data from 2 collections with aggregation mongoDB

I'm new as MongoDB, I have 2 collections: User and Video with below structure. When user like a video, video's _id will be added to liked_videos on user collection. liked_videos is an array of _id

video collection

{
    _id
    mp4_url,
    liked_count
}

User collection

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

How do I query to get the user's liked videos? Like below?

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

Thank you

You need to use $lookup to join collections and $size to get the array size

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

Working Mongo playground

Try this way

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

Query :

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

Output:

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

mongoplayground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM