I have the following structure for documents:
{
companyId: string,
language: string,
country: string,
template: string
}
I need to make a single call to the database to get a document but I have three ways to find it:
1 - {companyId: companyId, language: language}
2 - {companyId: companyId, language: languageCompany}
3 - {companyId: 'default', companyId: 'default', country: country}
And I want each way to be applied when the previous one has failed.
For example:
Database expample:
[{
companyId: 'companyId1',
language: 'en',
country: 'GB',
template: '....'
}, {
companyId: 'companyId2',
language: 'es',
country: 'ES',
template: '....'
}, {
companyId: 'default',
language: 'default',
country: 'ES',
template: '....'
}]
Input outputs examples:
Input 1
{
companyId: 'companyId1',
language: 'en',
languageCompany: 'en',
country: 'ES',
}
Output (apply first criteria):
{
companyId: 'companyId1',
language: 'en',
country: 'GB',
template: '....'
}
Input 2
{
companyId: 'companyId2',
language: 'en',
languageCompany: 'es',
country: 'ES',
}
Output (apply second criteria):
{
companyId: 'companyId1',
language: 'en',
country: 'GB',
template: '....'
}
Input 3
{
companyId: 'companyId2',
language: 'en',
languageCompany: 'es',
country: 'ES',
}
Output (apply third criteria):
{
companyId: 'companyId3',
language: 'en',
country: 'ES',
template: '....'
}
I just want to make a call It is not worth making the first call and if the second does not return anything, if the third does not return anything.
I let you this litter box in case it goes well for you: https://mongoplayground.net/p/CksyJE2nJsi
Thanks a lot for help :D
You can use facet to run multiple queries
db.collection.aggregate([
{
$facet: {
query1: [
{
$match: {
companyId: "companyId1",
language: "en"
}
},
{
$project: {
_id: 0
}
}
],
query2: [
{
$match: {
companyId: "companyId2",
language: "es"
}
},
{
$project: {
_id: 0
}
}
],
query3: [
{
$match: {
companyId: "default",
country: "ES"
}
},
{
$project: {
_id: 0
}
}
],
}
}
])
This will return an array with all the queries. You have to keep the first one that is not empty.
[
{
"query1": [
{
"companyId": "companyId1",
"country": "GB",
"language": "en",
"template": "...."
}
],
"query2": [
{
"companyId": "companyId2",
"country": "ES",
"language": "es",
"template": "...."
}
],
"query3": [
{
"companyId": "default",
"country": "ES",
"language": "default",
"template": "...."
}
]
}
]
https://mongoplayground.net/p/k3IAfiLi2Lf
In case your db had this data:
[
{
companyId: "othercompanyId1",
language: "en",
country: "GB",
template: "...."
},
{
companyId: "othercCompanyId2",
language: "es",
country: "ES",
template: "...."
},
{
companyId: "default",
language: "default",
country: "ES",
template: "...."
}
]
This would return information in the third query:
[
{
"query1": [],
"query2": [],
"query3": [
{
"companyId": "default",
"country": "ES",
"language": "default",
"template": "...."
}
]
}
]