您几乎自己在标签中回答了这个问题。MongoDB有一个$regex
运算符,它允许将正则表达式作为查询提交。因此,您查询包含“ Alex”的字符串,您可以这样做:
Books.find( { "authors": { "$regex": "Alex", "$options": "i" } }, function(err,docs) { } );您也可以这样做:
Books.find( { "authors": /Alex/i }, function(err,docs) { });两者都是有效的,并且与您以正确的受支持语法尝试的方式不同,如文档中所示。
但是,当然,如果您实际上是在问“如何仅对那些与字符串中的“ Alex”匹配的结果获取“数组”结果?” 那么这有点不同。
超过复杂的匹配 一个
数组元素是域聚合框架(或可能的MapReduce,但这是很慢),在需要“过滤器”的数组的内容。
您的开始大体相同。此处的关键是对$unwind
数组内容进行“反规范化”,以便能够作为单独的文档正确地“过滤”。然后,使用“匹配”文档重新构建数组。
Books.aggregate( [ // Match first to reduce documents to those where the array contains the match { "$match": { "authors": { "$regex": "Alex", "$options": i } }}, // Unwind to "de-normalize" the document per array element { "$unwind": "$authors" }, // Now filter those document for the elements that match { "$match": { "authors": { "$regex": "Alex", "$options": i } }}, // Group back as an array with only the matching elements { "$group": { "_id": "$_id", "title": { "$first": "$title" }, "authors": { "$push": "$authors" }, "subjects": { "$first": "$subjects" } }} ], function(err,results) { })


