I am struggling to find a neater way to doing this. I can of course do it with classic if-else condition but would like to somehow delegate it to mongodb and use a single db call to achieve it. I am using node js and native mongo driver.
Basically I want to do a find query in mongo db ->
- Query will return one document based on search criteria (like using id)
- If found return document if not do a fallback
- If a match is NOT found, another document will be searched on a different criteria and returned instead.
Example -> Take following couple of documents
[{
id: 1,
status: 'current'
},
{
id: 2,
status: 'default'
}
]
So, in this case if query is done for status. If find is queried with status as current it will fetch document with id 1. If find is queried with status done, since it's not present as a fallback it should return default.
I guess I can leverage the use of aggregations to achieve this? How to do it I am stuck at that part. Also is it possible to achieve it without aggregation?
Any help would be appreciated. Thanks!!