gpt4 book ai didi

MongoDB 找到最接近的匹配项

转载 作者:可可西里 更新时间:2023-11-01 10:16:11 27 4
gpt4 key购买 nike

我想知道是否可以通过最接近的匹配访问 MongoDB 中的文档。例如我的搜索查询总是包含:
名称
国家
城市

制定了以下规则:
1. name 必须始终匹配
2. 如果存在countrycity,country具有更高的优先级
3. 如果 countrycity 不匹配,仅考虑此文档,如果它们具有默认值(例如,对于 String: "")

示例查询:
名称 = "测试"
国家 = "美国"
城市 = "西雅图"

文件:

db.stuff.insert([
{
name:"Test",
country:"",
city:"Seattle"
},{
name:"Test3",
country:"USA",
city:"Seattle"
},{
name:"Test",
country:"USA",
city:""
},{
name:"Test",
country:"Germany",
city:"Seattle"
},{
name:"Test",
country:"USA",
city:"Washington"
}
])

它应该返回第三个文档

谢谢!

最佳答案

考虑到不确定的要求和相互矛盾的更新,答案更像是一个解决“是否可能”部分的指南。

应调整示例以满足预期。

db.stuff.aggregate([
{$match: {name: "Test"}}, // <== the fields that should always match
{$facet: {
matchedBoth: [
{$match: {country: "USA", city: "Seattle"}}, // <== bull's-eye
{$addFields: {weight: 10}} // <== 10 stones
],
matchedCity: [
{$match: {country: "", city: "Seattle"}}, // <== the $match may need to be improved, see below
{$addFields: {weight: 5}}
],
matchedCountry: [
{$match: {country: "USA", city: ""}},
{$addFields: {weight: 0}} // <== weightless, yet still a match
]
// add more rules here, if needed
}},
// get them together. Should list all rules from above
{$project: {doc: {$concatArrays: ["$matchedBoth", "$matchedCity", "$matchedCountry"]}}},
{$unwind: "$doc"}, // <== split them apart
{$sort: {"doc.weight": -1}}, // <== and order by weight, desc
// reshape to retrieve documents in its original format
{$project: {_id: "$doc._id", name: "$doc.name", country: "$doc.country", city: "$doc.city"}}
]);

问题中解释最少的部分会影响我们构建方面的方式。例如

{$match: {country: "", city: "西雅图"}}

匹配国家/地区明确存在且为空字符串的所有文档。

很有可能是

{$match: {country: {$ne: "USA"}, city: "Seattle"}}

获取所有具有匹配名称和城市以及任何国家/没有国家的文件,甚至

{$match: {$and: [{$or: [{country: null}, {country: ""}]}, {city: "Seattle"}]}}

等等

关于MongoDB 找到最接近的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720551/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com