您好,请帮我解决这个问题。 在 mongodb 中,我有一个像这样的集合:
data1= {
"string1":"abc",
"string2":"abcde"
}
data2= {
"string1":"abc",
"string2":"ftgr"
}
查询后我只想返回 data1,因为它的 string2
属性包含它的 string1
属性的内容。我怎样才能做到这一点?我应该使用 $where 还是使用正则表达式?如果有人能指点迷津,非常非常感激。
最佳答案
您可以使用 $where
执行此操作,方法是为 string1
创建一个 RegExp
,然后针对 string2
进行测试:
db.test.find({$where: 'RegExp(this.string1).test(this.string2)'})
但是,如果您使用的是 MongoDB 3.4+,则可以使用 $indexOfCP
更有效地完成此操作。聚合运算符:
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'
}
}}
])
关于javascript - 在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40984829/