-
Type:
New Feature
-
Resolution: Done
-
Priority:
Minor - P4
-
None
-
Affects Version/s: None
-
Component/s: Querying
-
Query
-
Fully Compatible
-
None
-
None
-
None
-
None
-
None
-
None
-
None
This is a proposal for a new feature that makes it possible to limit a result to only one object.
The limit is not applied via an standard sorting, but using a conditional operator with a list of parameters in decreasing priority.
Conditional operators like $in and $or will return only the first matched object.
The object can be a document or an array item.
The use case: multilanguage documents with support for fallback to a default language.
For this document:
{
"_id": 1,
"author": "John",
"languages": [
{
"code": "en",
"data": {
"title": "Title",
"contents": "My text."
}
},
{
"code": "fr",
"data": {
"title": "Le titre",
"contents": "Mon texte."
}
},
{
"code": "it",
"data": {
"title": "Titolo",
"contents": "Il mio testo."
}
}
]
}
I'd like to query conditionally for the user (website visitor) language, with a fallback to the default (app) language, but returning only one of them.
For that, I'd propose the new conditional operators $inFirst and $orFirst. They would return only the first match, evaluated from the left to the right.
I'll use $inFirst in the example below.
Suppose user's language is 'fr' and app default language is 'it'.
db.col.find( { _id:1, 'languages.code': { $inFirst: [ 'fr', 'it' ] } }, { author: 1, 'languages.$': 1 } )
Please note that the query features a (hopefully) future feature specified in SERVER-828.
Expected result:
{
"_id": 1,
"author": "John",
"languages": [
{
"code": "fr",
"data": {
"title": "Le titre",
"contents": "Mon texte."
}
}
]
}
I hope that this can be implemented without issues with indexes, parallel processing and sharded setups.