Thursday 26 November 2020

mongo aggregate based on conditions to filter the document for versioning

I am working on versioning, We have documents based on UUIDs andjobUuids, andjobUuids are the documents associated with the currently working user. I have some aggregate queries on these collections which I need to update based on the job UUIDs,

The results fetched by the aggregate query should be such that,

  • if the current usersjobUuid document does not exist then the master document with jobUuid: "default" will be returned(The document without any jobUuid),
  • if job uuid exists then only the document is returned.

I have a$match used to get these documents based on certain conditions, from those documents I need to filter out the documents based on the above conditions, and an example is shown below,

The data looks like this:

[
  {
    "uuid": "5cdb5a10-4f9b-4886-98c1-31d9889dd943",
    "name": "adam",
    "jobUuid": "default",
  },
  {
    "uuid": "5cdb5a10-4f9b-4886-98c1-31d9889dd943",
    "jobUuid": "d275781f-ed7f-4ce4-8f7e-a82e0e9c8f12",
    "name": "adam"
  },
  {
    "uuid": "b745baff-312b-4d53-9438-ae28358539dc",
    "name": "eve",
    "jobUuid": "default",
  },
  {
    "uuid": "b745baff-312b-4d53-9438-ae28358539dc",
    "jobUuid": "d275781f-ed7f-4ce4-8f7e-a82e0e9c8f12",
    "name": "eve"
  },
  {
    "uuid": "26cba689-7eb6-4a9e-a04e-24ede0309e50",
    "name": "john",
    "jobUuid": "default",
  }
]

Results for "jobUuid": "d275781f-ed7f-4ce4-8f7e-a82e0e9c8f12" should be:

[
  {
    "uuid": "5cdb5a10-4f9b-4886-98c1-31d9889dd943",
    "jobUuid": "d275781f-ed7f-4ce4-8f7e-a82e0e9c8f12",
    "name": "adam"
  },
  {
    "uuid": "b745baff-312b-4d53-9438-ae28358539dc",
    "jobUuid": "d275781f-ed7f-4ce4-8f7e-a82e0e9c8f12",
    "name": "eve"
  },
  {
    "uuid": "26cba689-7eb6-4a9e-a04e-24ede0309e50",
    "name": "john",
    "jobUuid": "default",
  }
]

Based on the conditions mentioned above, is it possible to filter the document within the aggregate query to extract the document of a specific job uuid?

Edit 1: I got the following solution, which is working fine, I want a better solution, eliminating all those nested conditions.

Edit 2: Updated the data with actual UUIDs and I just included only the name as another field, we do have n number of fields which are not relevant to include here but needed at the end.



from mongo aggregate based on conditions to filter the document for versioning

No comments:

Post a Comment