【问题标题】:MongoDB - Select where array contains a document fieldMongoDB - 选择数组包含文档字段的位置
【发布时间】:2018-09-22 05:43:46
【问题描述】:

我的collection("users") 中的文档是这样的:

{
    _id: ObjectID(...),
   verifiedFields:
   {
       email: ["user@example.com", "othermail@example.com"],
       phone: [...]
   },
   profiles:
   [
       {
           _id: ObjectID(...),
           fields: 
           {
                email: { value: "user@example.com" }
           }
       }
   ]
}

我现在想选择profiles.field.email.value 包含在其verifiedFields.email 中的所有用户。我想避免存储布尔值verified,因为应该允许用户拥有多个具有相同字段的配置文件,这会在以后导致复杂化。 提前致谢!

【问题讨论】:

  • 预期的输出应该是什么?
  • 只是用户集合中的一组文档,其中已验证电子邮件。

标签: arrays node.js mongodb


【解决方案1】:

您的查询是:

db.users.find({
  $expr: {$gt: [{$size: {$setIntersection: ['$profiles.fields.email.value', '$verifiedFields.email']}}, 0]}
})

此查询不使用索引,因此在性能问题上您需要添加 verified 字段。

请检查aggregation pipeline 和$expr 以更好地理解此查询。用于测试您的查询的管道是:

db.test.aggregate([
  { $addFields: {a : '$profiles.fields.email.value'}},
  { $addFields: {b: { $setIntersection: ['$a', '$verifiedFields.email']}}},
  { $match: {$expr: {$gt: [{$size: '$b'}, 0]}}}
])

【讨论】:

    【解决方案2】:

    这样的东西应该可以工作:

    collection('users').find({
        'profiles[0].fields.email.value': {$in: 'verifiedFields.email'}
    })
    

    【讨论】:

    • $in 只接受数组,不能从字符串中解释它们。
    猜你喜欢
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多