【问题标题】:fetching documents based on nested subdoc array value根据嵌套的 subdoc 数组值获取文档
【发布时间】:2017-01-23 05:10:21
【问题描述】:

我正在尝试根据子文档数组值获取集合中的所有文档。这是我正在寻找的集合中的数据结构:

{
    _id: ObjectId('...'),
    name: "my event",
    members:
    [
        {
            _id: ObjectId('...'),
            name: "family",
            users: [ObjectId('...'),ObjectId('...'),ObjectId('...')]
        },
        {
            _id: ObjectId('...'),
            name: "work",
            users: [ObjectId('...'),ObjectId('...'),ObjectId('...')]
        }
    ]
}

我应该指出,这些对象的架构是这样定义的:

事件:

{
    name: { type: String },
    members: {type: [{ type: ObjectId, ref: 'MemberGroup' }], default:[] }
}

会员组:

{
    name: { type: String },
    users: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
}

当然,User 只是一个带有 id 的任意对象。

我要获取的内容:我想检索在其 member.users 字段中具有特定用户 ID 的所有事件。

我不确定它的事件是否可能在一次调用中发生,但这是我尝试过的:

var userId = new mongoose.Schema.ObjectId('57d9503ef10d5ffc08d6b8cc');
events.find({members: { $elemMatch : { users: { $in: [userId]} } }})

此语法有效但不返回任何元素,即使我知道有匹配的元素(使用 robomongo 可视化数据库)

【问题讨论】:

  • 语法错误 - 4 个左大括号和 5 个右大括号(也缺少右右括号)。我修正了语法并且它有效:db.events.find({ members: { $elemMatch: { users: { $in: [userId] } } }})
  • @Tom 不,那只是复制粘贴错字
  • 我明白,但正如我所说,当我运行此查询时,它可以工作。所以我猜你忘记了别的东西......

标签: mongodb mongoose


【解决方案1】:

所以在 stackoverflow 中经过长时间的搜索后,我在这里遇到了很好的答案:

MongoDB: How to find out if an array field contains an element?

我的查询更改为以下内容,这给了我想要的结果:

var userId = new mongoose.Schema.ObjectId('57d9503ef10d5ffc08d6b8cc');
events.find({}, {members: { $elemMatch : { users: { $eq: userId} } }})

注意使用第二个 find 参数来指定查询限制,而不是第一个(这很奇怪)

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2017-12-12
    • 1970-01-01
    • 2023-03-05
    • 2013-12-31
    • 1970-01-01
    相关资源
    最近更新 更多