在 Mongodb 聚合管道中的 expr 中使用正则表达式
Use regex in expr in Mongodb aggragtion pipeline
我有国家Table
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e0"),
"county" : "india"
},
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e1"),
"county" : "china"
}
和城市Table
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e0"),
"county_name" : "India"
},
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e1"),
"county_name" : "China"
}
In Country Table Country name 是小写字母,In City Table Country Name 是大写字母。那么现在如何使用类似条件来连接两个具有匹配相同名称的集合。
前任。获取印度的数据 Like India
db.getCollection('countryTable').aggregate([
{
$lookup: {
from: "cityTable",
let: { county: "$county" },
pipeline: [{
$match: {
"$expr": {
"$regexMatch": {
"input": "$county_name",
"regex": "$$county",
"options": "i"
}
}
}
}],
as: "citydetails"
}
},
{ $unwind: "$citydetails" }
])
使用 MongoDB v4.0,您可以使用 $toLower
在子管道中执行 $match
db.countryTable.aggregate([
{
$lookup: {
from: "cityTable",
let: {
county: "$county"
},
pipeline: [
{
$match: {
"$expr": {
$eq: [
{
"$toLower": "$$county"
},
{
"$toLower": "$county_name"
}
]
}
}
}
],
as: "citydetails"
}
},
{
$unwind: "$citydetails"
}
])
这里是Mongo playground供大家参考。
我有国家Table
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e0"),
"county" : "india"
},
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e1"),
"county" : "china"
}
和城市Table
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e0"),
"county_name" : "India"
},
{
"_id" : ObjectId("627cd43f48aea72fdc0d88e1"),
"county_name" : "China"
}
In Country Table Country name 是小写字母,In City Table Country Name 是大写字母。那么现在如何使用类似条件来连接两个具有匹配相同名称的集合。 前任。获取印度的数据 Like India
db.getCollection('countryTable').aggregate([
{
$lookup: {
from: "cityTable",
let: { county: "$county" },
pipeline: [{
$match: {
"$expr": {
"$regexMatch": {
"input": "$county_name",
"regex": "$$county",
"options": "i"
}
}
}
}],
as: "citydetails"
}
},
{ $unwind: "$citydetails" }
])
使用 MongoDB v4.0,您可以使用 $toLower
$match
db.countryTable.aggregate([
{
$lookup: {
from: "cityTable",
let: {
county: "$county"
},
pipeline: [
{
$match: {
"$expr": {
$eq: [
{
"$toLower": "$$county"
},
{
"$toLower": "$county_name"
}
]
}
}
}
],
as: "citydetails"
}
},
{
$unwind: "$citydetails"
}
])
这里是Mongo playground供大家参考。