选择与mongodb中两个字段的concat值匹配的记录 [英] Select records matching concat value of two fields in mongodb

查看:458
本文介绍了选择与mongodb中两个字段的concat值匹配的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在MongoDB上执行类似的操作?

Is there a way to do something like this on MongoDB?

select * from table where concat(field1, field2) = 'value'

为了澄清,我有一个全名数组,但是文档的名字和姓氏分开,所以我想做类似的事情:

To clarify, I have an array of full names, but the documents have firstname and lastname separate, so I want to do something like:

select * from table where concat(firstname, lastname) in ([ARRAY OF NAMES])


推荐答案

您只能使用聚合框架,而不能使用常规查找。

You can only do it with aggregation framework, not with regular find.

db.coll.aggregate({$project:{newField:{$concat:["$field1","$field2"]}}},
                  {$match:{newField:"value"}} 
);

请注意,这将无法使用任何索引,因为不支持计算索引

Note that this will not be able to use any indexes, since there is no support for indexes on computed values in MongoDB (yet).

如果您在 field1 上有一个索引,并且您知道期望多少个字符field1有助于产生,您可以像这样提高聚合的性能:

If you have an index on field1 and you know how many characters you expect field1 to contribute to value you can improve performance of this aggregation like this:

db.coll.aggregate({$match:{field1:/^val/}},
                  {$project:{newField:{$concat:["$field1","$field2"]}}},
                  {$match:{newField:"value"}} 
);

其中 val 是值的第一部分字符串(尽管您不能比较的字符数不能超过 field1 的最短值。

where val is first part of "value" string (you must not compare more characters than the shortest possible value of field1 though.

编辑从3.6版开始,您可以使用 $ expr 表达式进行查找:

EDIT as of version 3.6 you can do this in find using the $expr expression:

db.coll.find({$expr:{$eq:["value", {$concat:["$field1", "$field2"]}]}})

这篇关于选择与mongodb中两个字段的concat值匹配的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆