简体   繁体   中英

Search through list of objects in efficient way mongo

I have a json that looks a bit like this in meteor.

{
  "_id": "someid",
  "createdAt": ISODate("2015-03-10T14:26:02.430Z"),
  "emails": [{
      "address": "raven@corvid.com",
      "verified": false
    }, {
      "address": "crow@corvid.com",
       "verified": false
  }]
}

I want to search the database and find if anyone has a given email, say, crow@corvid.com . If it were just a static value, you could do Meteor.users.findOne({ email: "crow@corvid.com" }); , but the list makes it more complicated.

What is the efficient way to do this?

您可以使用$ elemMatch运算符执行此操作,以匹配包含crow@corvid.com作为地址值的文档。

Meteor.users.findOne({ emails: {$elemMatch: {address:"crow@corvid.com" }}})

您还可以为数据库建立索引,可以为嵌入的文档建立索引,您的案例是一个数组Meteor.users.createIndex( { "emails" : 1 } )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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