Home > Net >  How do I do mongo aggregation for this particular case?
How do I do mongo aggregation for this particular case?

Time:02-25

I got a collection 'A' which has documents like

{
 "_id": <>,
"entity_id": <>,
"user_id" <>,
created_at:<>
}

I need to get a certain property 'organization_name' from collection 'B' whose _id matches with "user_id" of collection 'A' documents

make finally I expect this output:

{
_id:<>,
organization_name:<>,
user_id:<>,
entity_id:<>
created_at:<>
}

initial matching criterion can be {created_at:{$gt:<>,$lt:<>}}

CodePudding user response:

You can try using the aggregation framework with $match,$lookup and $unwind stages. I think something like this is what are you looking for:

db.a_collection_name.aggregate([
    {$match: {created_at:{$gt:<>,$lt:<>}}},
    {$lookup: {
       from:  <b_collection_name>,
       localField: "user_id",
       foreignField: "_id",
       as: "output"
    }},
    {$unwind: {
       path: '$output',
    }}
])

$match sets the match condition, the filter stage in operations like find. $lookup is basically a left outer join or a populate, and $unwind deconstructs the array obtained in the previous lookup stage. Check the official mongodb aggregation framework documentation if you want to learn more https://docs.mongodb.com/manual/aggregation/. Mongodb University has a aggregation course that is very cool https://university.mongodb.com/courses/M121/about

CodePudding user response:

Your code works fine.

db.collection.aggregate([
  {
    "$match": {
      "created_at": {
        "$gte": "2021-02-01",
        "$lt": "2022-02-01"
      }
    }
  },
  {
    "$lookup": {
      "from": "people",
      "localField": "user_id",
      "foreignField": "_id",
      "as": "fromPeople"
    }
  },
  {
    "$unwind": "$fromPeople"
  },
  {
    "$match": {
      "fromPeople.organization_type": "school"
    }
  },
  {
    "$project": {
      "fromPeople.organization_type": 1,
      "fromPeople.organization": 1,
      "user_id": 1
    }
  }
])

mongoplayground

  • Related