1 回答

TA贡献1848条经验 获得超10个赞
$regex很可能只适用于字符串。如果你看一下 https://docs.mongodb.com/manual/reference/operator/query/regex/ 单词“字符串”是斜体的:
为查询中的模式匹配字符串提供正则表达式功能。
所以:
irb(main):034:0> a['foo'].find.first
=> {"_id"=>BSON::ObjectId('6068e59d4896683bab61ddbe'), "test"=>1}
irb(main):035:0> a['foo'].find(_id: /606/).first
=> nil
可以使用 https://docs.mongodb.com/manual/reference/operator/aggregation/convert/(和聚合管道)将值转换为字符串类型:
irb(main):037:0> a['foo'].aggregate([{'$set'=>{_id:{'$convert'=>{input:'$_id',to:'string'}}}},{'$match':{_id:/606/}}
]).to_a
=> [{"_id"=>"6068e59d4896683bab61ddbe", "test"=>1}]
请注意,此类型将_id转换为字符串,如果在其原始 ObjectId 类型中需要它,则需要将其$convert。
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报