查询MongoDB中的本地化数据 [英] Querying localized data in MongoDB
问题描述
具有本地化"的数据,如下所示:
Having data 'localized' like this:
{
"cs": [
{
"cID": "00001",
"title": {
"en": "title en1",
"de": "title de1"
},
"desc": {
"en": "desc en1",
"de": "desc de1"
},
"startDate": 20210801,
"endDate": 20210809,
"numDays": 8
},
{
"cID": "00002",
"title": {
"en": "title en2",
"de": "title de2"
},
"desc": {
"en": "desc en2",
"de": "desc de2"
},
"startDate": 20210701,
"endDate": 20210715,
"numDays": 14
}
]
}
考虑用户区域设置(传递给查询作为参数)的最佳方法是什么?例如,如果"en"为如果已通过,则查询应针对"cID"返回此值:"00001":
What would be the best way to query this taking user locale (passed to query as param) into account? For example, if "en" was passed, the query should return this for "cID": "00001" :
{
"cID": "00001",
"title": "title en1",
"desc": "desc en1",
"startDate": 20210801,
"endDate": 20210809,
"numDays": 8
}
理想情况下,查询应该是通用"查询,而不是专门过滤"title"和"desc"对象.
Ideally, the query should be 'generic' and not filter specifically the 'title' and 'desc' objects.
我知道:
db.cs.find({
"cID": "00001"
},
{
"_id": 0,
"cID": 1,
"title": "$title.en",
"desc": "$desc.en",
"startDate": 1,
"endDate": 1,
"numDays": 1
})
会给我的
[
{
"cID": "00001",
"desc": "desc en1",
"endDate": 2.0210809e+07,
"numDays": 8,
"startDate": 2.0210801e+07,
"title": "title en1"
}
]
但是要用不同的语言环境和不同的数据模型在不同的查询中处理它会很棘手.
but it would be tricky to handle it with many locales and different data models in different queries.
蒙哥游乐场: https://mongoplayground.net/p/9erh-VYiOO4
推荐答案
您可以尝试
-
$ reduce
迭代title
数组的循环,$ cond
匹配local
的循环并将匹配结果返回给值,描述数组的处理相同
$reduce
to iterate loop oftitle
array,$cond
to matchlocal
and return match result to value, same process for description array
{
$addFields: {
title: {
$reduce: {
input: "$title",
initialValue: "",
in: {
$cond: [{ $eq: ["$$this.locale", "pl"] }, "$$this.value", "$$value"]
}
}
},
description: {
$reduce: {
input: "$description",
initialValue: "",
in: {
$cond: [{ $eq: ["$$this.locale", "pl"] }, "$$this.value", "$$value"]
}
}
}
}
}
对于通用选项,您可以使函数具有两个参数,第一个是带有 $
符号的输入字段,第二个是语言环境:
for the generic option you can make a function with two parameters first one is input field with $
sign and second one is locale:
function languageFilter(inputField, locale) {
return {
$reduce: {
input: inputField,
initialValue: "",
in: {
$cond: [{ $eq: ["$$this.locale", locale] }, "$$this.value", "$$value"]
}
}
};
}
您的最终查询将是:
let locale = "pl";
db.cs.aggregate([
{ $match: { cID: "00001" } },
{
$addFields: {
title: languageFilter("$title", locale)
description: languageFilter("$description", locale)
}
}
]);
这篇关于查询MongoDB中的本地化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!