Javascript 在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段执行查询
你好,请帮我做这个。 在mongodb中,我有这样一个集合:Javascript 在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段执行查询,javascript,mongodb,Javascript,Mongodb,你好,请帮我做这个。 在mongodb中,我有这样一个集合: data1= { "string1":"abc", "string2":"abcde" } data2= { "string1":"abc", "string2":"ftgr" } 在查询之后,我只想返回data1,因为它的string2属性包含它的string1属性的内容。我怎样才能做到这一点?我应该在何处使用$where还是使用regex?如果有人能给我小费,我将不胜感激 您可以使用$where
data1= {
"string1":"abc",
"string2":"abcde"
}
data2= {
"string1":"abc",
"string2":"ftgr"
}
在查询之后,我只想返回data1,因为它的
string2
属性包含它的string1
属性的内容。我怎样才能做到这一点?我应该在何处使用$where还是使用regex?如果有人能给我小费,我将不胜感激 您可以使用$where
为string1
创建一个RegExp
,然后对string2
进行测试:
db.test.find({$where: 'RegExp(this.string1).test(this.string2)'})
但是,如果您使用的是MongoDB 3.4+,则可以通过使用聚合操作符来更有效地执行此操作:
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'
}
}}
])
我不太清楚您是希望查询完成此操作,还是希望在查询完成后过滤结果。此外,这里似乎已使用$where或聚合来回答此问题: