Mongodb-属性值内的聚合匹配



MongoDB数据:

{
"_id" : ObjectId("123"),
"attr" : [ 
{
"nameLable" : "First Name",
"userEnteredValue" : [ 
"Amanda"
],
"rowNumber":"1"
}, 
{
"nameLable" : "Last Name",
"userEnteredValue" : [ 
"Peter"
],
"rowNumber":"1"
}, 
{
"nameLable" : "First Name",
"userEnteredValue" : [ 
"Sandra"
],
"rowNumber":"2"
}, 
{
"nameLable" : "Last Name",
"userEnteredValue" : [ 
"Peter"
],
"rowNumber":"2"
}
]
}

匹配(名字等于"Amanda",姓氏等于"Peter"(->匹配应该发生在rowNumber中,这样我将获得rowNumber1记录,但现在我将两行都作为"匹配";Peter";恰好在两个";rowNumber;属性

标准代码:

Criteria cr = Criteria.where("attr").elemMatch(Criteria.where("nameLable").is(map.get("value1")).and("userEnteredValue").regex(map.get("value2").trim(), "i"); //Inside loop
AggregationOperation match = Aggregation.match(Criteria.where("testId").is("test").andOperator(cr.toArray(new Criteria[criteria.size()])));

DB查询上述搜索条件匹配:

db.Col1.aggregate([
{
"$match":{
"testId":"test",
"$and":[
{
"attr":{
"$elemMatch":{
"nameLable":"First Name",
"userEnteredValue":{
"$regex":"Amanda",
"$options":"i"
}
}
}
},
{
"attr":{
"$elemMatch":{
"nameLable":"Last Name",
"userEnteredValue":{
"$regex":"Peter",
"$options":"i"
}
}
}
}
]
}
}
]
)

请让我知道我们如何在";rowNumber;属性

让我首先建议您重新考虑您的文档结构,我不知道您的产品,但这种结构非常独特,肯定会让大多数"简单的";我认为访问模式执行起来非常麻烦。这一点在我的回答中会很明显。

因此,您只需要在数组中存在2个独立元素的当前查询,正如您所提到的,您想要相同的rowNumber,由于文档结构的原因,这不是真正可查询的,我们必须首先使用您的查询来匹配";潜在的";匹配的文档。这时,我们可以过滤匹配的行,看看是否同时匹配了名字和姓氏。

最后,我们可以从结果中筛选出不匹配的行,这是管道:

db.collection.aggregate([
{
"$match": {
"testId": "test",
"$and": [
{
"attr": {
"$elemMatch": {
"nameLable": "First Name",
"userEnteredValue": {
"$regex": "Amanda",
"$options": "i"
}
}
}
},
{
"attr": {
"$elemMatch": {
"nameLable": "Last Name",
"userEnteredValue": {
"$regex": "Peter",
"$options": "i"
}
}
}
}
]
}
},
{
$addFields: {
goodRows: {
"$setIntersection": [
{
$map: {
input: {
$filter: {
input: "$attr",
cond: {
$and: [
{
$eq: [
"$$this.nameLable",
"First Name"
]
},
{
"$regexMatch": {
"input": {
"$arrayElemAt": [
"$$this.userEnteredValue",
0
]
},
"regex": "Amanda",
"options": "i"
}
}
]
}
}
},
in: "$$this.rowNumber"
}
},
{
$map: {
input: {
$filter: {
input: "$attr",
cond: {
$and: [
{
$eq: [
"$$this.nameLable",
"Last Name"
]
},
{
"$regexMatch": {
"input": {
"$arrayElemAt": [
"$$this.userEnteredValue",
0
]
},
"regex": "Peter",
"options": "i"
}
}
]
}
}
},
in: "$$this.rowNumber"
}
}
]
}
}
},
{
$match: {
$expr: {
$gt: [
{
$size: "$goodRows"
},
0
]
}
}
},
{
$addFields: {
attr: {
$filter: {
input: "$attr",
cond: {
$in: [
"$$this.rowNumber",
"$goodRows"
]
}
}
}
}
}
])

Mongo游乐场

最新更新