我想在名为的字段上搜索一组文档SERVICES
。
当我搜索时,以及
如果:我发现字符串开头的第一个单词是Mail
orEnvelopes delivered
或Lost suitcase
or Found mail
。
然后:我在字符串中添加SERVICES
句点和LAGUAGES
字段的字符串值。LAGUAGES
字符串是:“需要立即采取行动”。
样本数据:
/* 1 */
{
"SERVICES" : "Mail has been packaged and sitting in mail room",
"LAGUAGES" : "Needs immediate action"
}
/* 2 */
{
"SERVICES" : "Envelopes delivered to client but were not signed for by anyone",
"LAGUAGES" : "Needs immediate action"
}
/* 3 */
{
"SERVICES" : "There were problems with the client's luggage",
"LAGUAGES" : "Needs immediate action"
}
/* 4 */
{
"SERVICES" : "Lost suitcase at airport while in transit",
"LAGUAGES" : "Needs immediate action"
}
/* 5 */
{
"SERVICES" : "Found mail sitting at airport mailing room",
"LAGUAGES" : "Needs immediate action"
}
要求的输出:
/* 1 */
{
"SERVICES" : "Mail has been packaged and sitting in mail room. Needs immediate action"
}
/* 2 */
{
"SERVICES" : "Envelopes delivered to client but were not signed for by anyone. Needs immediate action"
}
/* 3 */
{
"SERVICES" : "Lost suitcase at airport while in transit. Needs immediate action"
}
/* 4 */
{
"SERVICES" : "Found mail sitting at airport mailing room. Needs immediate action"
}
尝试过以下查询:
我$match
只是为了过滤信息而进行了第一次操作$OR
,但似乎仅对语句中的最后一个进行了过滤。需要帮忙。
{
$match: {
$or: [
{
SERVICES: { $regex: "Mail.* " },
SERVICES: { $regex: "Envelopes delivered.* " },
SERVICES: { $regex: "Lost suitcase. * " },
SERVICES: { $regex: "Found mail. * " },
},
];
}
}
如何搜索这些字符串并返回以上输出。谢谢。
您需要使用聚合的$ concat运算符:
db.collection.aggregate([
{
$match: {
$or: [
{
SERVICES: { $regex: /^Mail/ }
},
{
SERVICES: { $regex: /^Envelopes delivered/ }
},
{
SERVICES: { regex: /^Lost suitcase/ }
},
{
SERVICES: { $regex: /^Found mail/ }
}
]
}
},
/** `$addFields` will re-create `SERVICES` field with new concated string value
* Or if you just want `SERVICES` field then use `$project` with `_id :0 ` */
{$addFields : {SERVICES : {$concat : ['$SERVICES','.',' ','$LAGUAGES']}}}
])
或者您可以使用$in
代替$or
:
db.collection.aggregate([
{ $match: { SERVICES: { $in: [/^Mail/, /^Envelopes delivered/, /^Lost suitcase/, /^Found mail/] } } } ,
{$addFields : {SERVICES : {$concat : ['$SERVICES', '.', ' ','$LAGUAGES']}}}
]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句