在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询 [英] In MongoDB, how to perform query based on if one string field contains another
问题描述
您好,请帮助我. 在mongodb中,我有一个这样的集合:
Hello please help me with this. In mongodb, I have a collection like this:
data1= {
"string1":"abc",
"string2":"abcde"
}
data2= {
"string1":"abc",
"string2":"ftgr"
}
查询后,我只想返回data1,因为它的string2
属性包含其string1
属性的内容.我该如何进行这项工作?我应该使用$ where还是使用正则表达式?如果有人可以给小费,我将非常感激.
After the query I only want to return data1 because it's string2
property contains the contents of it's string1
property. How can I make this work? Should I use $where or using regex? Very very appreciated if someone can point a tip.
推荐答案
您可以通过为string1
创建一个RegExp
然后针对string2
对其进行测试,来对$where
进行此操作:
You can do this with $where
by creating a RegExp
for string1
and then testing it against string2
:
db.test.find({$where: 'RegExp(this.string1).test(this.string2)'})
However, if you're using MongoDB 3.4+ you can do this more efficiently by using the $indexOfCP
aggregation operator:
db.test.aggregate([
// Project the index of where string1 appears in string2, along with the original doc.
{$project: {foundIndex: {$indexOfCP: ['$string2', '$string1']}, doc: '$$ROOT'}},
// Filter out the docs where the string wasn't found
{$match: {foundIndex: {$ne: -1}}},
// Promote the original doc back to the root
{$replaceRoot: {newRoot: '$doc'}}
])
或更直接使用$redact
:
db.test.aggregate([
{$redact: {
$cond: {
if: { $eq: [{$indexOfCP: ['$string2', '$string1']}, -1]},
then: '$$PRUNE',
else: '$$KEEP'
}
}}
])
这篇关于在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!