简体   繁体   中英

Get the MongoDB collection field value based on if another collection exists or not

I have two collections like this:

collection_1

[{
   name: "p1",
   use: "u1"
},
{
   name: "p2",
   use: "u2"
}, ...]

collection_2

 [{
    user_name: "p1",
    user_id: "Id1"
    date: "DATE"
 },{
    user_name: "p2",
    user_id: "Id2"
    date: "DATE"
 },{
    user_name: "p3",
    user_id: "Id1"
    date: "DATE"
 }, ...]

I wanted the favorite field as boolean if the collection_1 name field matches the collection_2 user_name field and where user_id is equal to "Id1".

Is this possible in aggregations or other better methods in MongoDB?

//result 
[{
   name: "p1",
   is_favorite: true
},{
   name: "p2",
   is_favorite: false,
},{
   name: "p2",
   is_favorite: true,
}]
  1. $lookup - Collection col1 (with key: name ) join with col2 (with key: user_name ).

  2. $project - Decorate the output documents. For the is_favorite field, use the $in operator to check whether Id1 is in the col2.user_id array.

db.col1.aggregate([
  {
    $lookup: {
      from: "col2",
      localField: "name",
      foreignField: "user_name",
      as: "col2"
    }
  },
  {
    $project: {
      name: 1,
      is_favorite: {
        $in: [
          "Id1",
          "$col2.user_id"
        ]
      }
    }
  }
])

Sample Mongo Playground

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