为什么 elem_match 返回 0 个元素?
Why elem_match is returning 0 elements?
我正在尝试从一组对象中获取一条记录结果,但在遵循 Mongoid 文档之后,我不知道还能尝试什么。
我有这个元素:
> contacts
=> #<Contact _id: 55ace6bc6xx, device_fields: {"app_id"=>"55ace6bc65195efc8200xxxx"}, created_at: 2015-07-20 12:17:00
UTC, updated_at: 2015-07-20 12:17:00 UTC, name_first: "Kory",
name_last: "Funk", ...>
这个匹配器列表:
> apps = []
> apps << App.where(id: "55ace6bc65195efc8200xxxx").first.id
=> ["55ace6bc65195efc8200xxxx"]
此代码试图获取匹配的元素:
> contacts.elem_match(device_fields: {:app_id.in => apps }).to_a
=> []
> contacts.elem_match(device_fields: { "app_id": "55ace6bc65195efc8200xxxx"}).to_a
=> []
如果有一个匹配的数组,为什么返回一个空数组?
我无法用match_elem
方法解决这个问题,所以最后我决定通过and
来解决。我对这个解决方案不是很满意,我仍然不明白为什么 match_elem
没有返回记录,但至少我找到了解除阻止此功能的解决方案。
contacts.and(:device_fields.exists => true,
:device_fields.nin => ['', nil],
:"device_fields.app_id".in => apps).to_a
根据官方mongodb manual
The $elemMatch operator matches documents that contain an array field
并且您试图将它与哈希字段一起使用,所以您基本上误解了这个选择。所以没有匹配的对象。
你应该这样做:
contacts.where(:'device_fields.app_id'.in => apps).to_a
这里不需要 elemMatch
。它用于通过部分匹配查找对象数组元素(您不需要完全对象相等,而只需要一个或几个字段)
这应该适合你的情况。
contacts.where('device_fields.app_id' => {'$in' => apps})
我正在尝试从一组对象中获取一条记录结果,但在遵循 Mongoid 文档之后,我不知道还能尝试什么。
我有这个元素:
> contacts
=> #<Contact _id: 55ace6bc6xx, device_fields: {"app_id"=>"55ace6bc65195efc8200xxxx"}, created_at: 2015-07-20 12:17:00
UTC, updated_at: 2015-07-20 12:17:00 UTC, name_first: "Kory",
name_last: "Funk", ...>
这个匹配器列表:
> apps = []
> apps << App.where(id: "55ace6bc65195efc8200xxxx").first.id
=> ["55ace6bc65195efc8200xxxx"]
此代码试图获取匹配的元素:
> contacts.elem_match(device_fields: {:app_id.in => apps }).to_a
=> []
> contacts.elem_match(device_fields: { "app_id": "55ace6bc65195efc8200xxxx"}).to_a
=> []
如果有一个匹配的数组,为什么返回一个空数组?
我无法用match_elem
方法解决这个问题,所以最后我决定通过and
来解决。我对这个解决方案不是很满意,我仍然不明白为什么 match_elem
没有返回记录,但至少我找到了解除阻止此功能的解决方案。
contacts.and(:device_fields.exists => true,
:device_fields.nin => ['', nil],
:"device_fields.app_id".in => apps).to_a
根据官方mongodb manual
The $elemMatch operator matches documents that contain an array field
并且您试图将它与哈希字段一起使用,所以您基本上误解了这个选择。所以没有匹配的对象。
你应该这样做:
contacts.where(:'device_fields.app_id'.in => apps).to_a
这里不需要 elemMatch
。它用于通过部分匹配查找对象数组元素(您不需要完全对象相等,而只需要一个或几个字段)
这应该适合你的情况。
contacts.where('device_fields.app_id' => {'$in' => apps})