我正在尝试将文档与查询中使用数组字段的 Mongoid/Mongodb 进行匹配。我一直在努力使用 $elemMatch
但似乎无法得到它。
上下文
- 一个
项目
可以有admin
、member
、reader
用户 - 这些用户由
项目
(HABTM) 引用 - 我希望能够找到以下项目:
- 用户 A 是
admin
- 用户 B 是
admin
或member
- ..等等..
- 用户 A 是
例子
给定来自 Rails 控制台的 Project
文档:
[#<Project _id: 4f44355a9f5b7f385a000003,
_type: nil, name: "Project ABC",
desc: "some description",
admin_ids:
[BSON::ObjectId('123')],
member_ids:
[BSON::ObjectId('456'),
BSON::ObjectId('789')],
reader_ids: []
>]
我有以下代码:
@projects = Project.any_of({:admin_ids => [current_user.id]},
{:member_ids => [current_user.id]}).entries
在 admin_ids
和 member_ids
中匹配 current_user.id
只要只有一个值在任一数组中。根据上面的代码:
- 尝试匹配用户
'123'
给出正确的结果 - 尝试匹配用户
'456'
没有结果(不正确)
$elemMatch
根据研究,我认为我应该使用 $elemMatch
但我遗漏了一些东西。
根据上面的项目
文档代码:
// test case: this works with array of one
Project.all(conditions: {:admin_ids => "123"}).entries
// failure case: empty result
Project.all(conditions: {:member_ids => {'$elemMatch' => {:id => '456' } }}).entries
// failure case: empty result
Project.all(conditions: {:member_ids => {'$elemMatch' => {:id => BSON::ObjectId('4f44a4019f5b7f3d5200000d') } }}).entries
最佳答案
查询时需要去掉数组。
@projects = Project.any_of({:admin_ids => current_user.id},
{:member_ids => current_user.id}).entries
这应该有效。
关于ruby-on-rails - 如何在查询中使用数组字段匹配 mongoid 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9392438/