简体   繁体   English

MongoDB - 选择数组包含文档字段的位置

[英]MongoDB - Select where array contains a document field

The documents in my collection("users") look like this:我的collection("users")的文档如下所示:

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

I would like to now select all users who's profiles.field.email.value is contained within their verifiedFields.email .我现在想选择所有用户的profiles.field.email.value包含在他们的verifiedFields.email I would like to avoid having to store a boolean verified as the user should be allowed to have multiple profiles with the same fields and this would cause complications later on.我想避免必须存储verified的布尔值,因为应该允许用户拥有多个具有相同字段的配置文件,这会在以后导致复杂化。 Thanks in advance!提前致谢!

Your query is:您的查询是:

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

This query doesn't use indexes, so on performance issue you will need add verified field.此查询不使用索引,因此在性能问题上,您需要添加verified字段。

Please, checkaggregation pipeline and $expr for better understanding this query.请检查聚合管道$expr以更好地理解此查询。 Pipeline used for testing your query was:用于测试查询的管道是:

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

something like this should work:这样的事情应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM