我在MongoDB中有多语言数据,格式如
{
"_id" : ObjectId("56ebd619e07925a2286c1c3c"),
"translation" : [
{
"language" : "english",
"name" : "shahid Afridi",
"desc" : "batsmen",
"player" : "capten"
},
{
"language" : "spanish",
"name" : "shhid Ofridi",
"desc" : "batsmeen",
"player" : "capteen"
},
{
"language" : "french",
"name" : "hhid afrede is best",
"desc" : "batsmin",
"player" : "captn"
}
]
}
假设是西班牙语用户,那么我的查询是
db.getCollection('t.m').find({$text: { $search: "best",$language: "es", }})
问题是它在整个翻译数组中搜索(不是法语) 我也尝试过只搜索并返回数组中的特定语言文档我也尝试过基于其他SO问题,但没有运气,即
db.getCollection('t.m').find({$text: { $search: "capten",$language: "es", },translation: {$elemMatch: {language: "english"}}})
我的问题有部分
记得我为name,desc和player创建文本索引。任何帮助将不胜感激。
答案 0 :(得分:2)
我正在阅读您的帖子,因为您希望根据子文档中的语言选择来限制全文搜索。 假设你有MongoDB 3.2 +
,你可以使用聚合框架来实现如果是MongoDB 3.2 +
db.doc.aggregate([
{$match:{$text: {$search:"shahid Afridi"}}},
{$project:
{translation:
{$filter:
{input: "$translation", as:"tr", cond: { $eq : ["$$tr.language", "english"]}}
}
}
}])
MongoDB< 3.2
db.doc.aggregate([
{$match:{$text: {$search:"shahid Afridi"}}},
{$unwind:"$translation"},
{$match:{"translation.language":"english"}}
])
此查询将发出:
{
"_id" : ObjectId("56ebd619e07925a2286c1c3c"),
"translation" : [
{
"language" : "english",
"name" : "shahid Afridi",
"desc" : "batsmen",
"player" : "capten"
}
]
}