MongoDB(Mongoose & Mongo 客户端 PHP)在 concat 字段中搜索

MongoDB (Mongoose & Mongo Client PHP) search in concat field

给定像 { name: String, middlename: String, lastname: String } 这样的结构,在 mongo 中是否有办法在 mongo 中为节点和在 php 中搜索字段串联中的术语,例如在 mysql 我可以做类似

select * from persons 
    where concat_ws(' ',name, middlename, lastname) like '%John A%' OR
    concat_ws(' ',lastname, middlename, name) like '%John A%'
    group by id

这样我就不需要明确地为每个字段输入一个,但我不知道如何在 mongo

中完成类似的事情

您可以在 find() 查询中使用 $where 运算符:

db.persons.find({$where:function(){
    var search = /John A/;
    var matchA = (this.name+" "+this.middlename+" "+this.lastname).match(search);
    var matchB = (this.lastname+" "+this.middlename+" "+this.name).match(search);
    return !!(matchA || matchB);
}})

或者,您可以汇总结果。

MongoDb聚合管道:

var search = /John A/;
db.persons.aggregate([
{$project:{"concat_name_a":{$concat:["$name"," ","$middlename"," ","$lastname"]},
           "concat_name_b":{$concat:["$lastname"," ","$middlename"," ","$name"]},
           "name":1,"middlename":1,"lastname":1}},
{$match:{$or:[{"concat_name_a":search},{"concat_name_b":search}]}},
{$project:{"name":1,"middlename":1,"lastname":1}}
])

这里采用任何一种方法都可以,因为这两种方法都不能使用集合中的任何索引。