murvinlai
murvinlai

Reputation: 50385

How to "find" a collection and compare value with its inner object in MongoDB?

Hmmm I don't know how to clearly state the title. hopefully the following explanation will be better.

I have a schema like that:

company = new Schema {
  name: String,
  contact: {}
}

For example:

{
  name:'cnn'
  contact: {
      address:'whatever',
      phone1: '1-800-123-1234',
      url: 'cnn.com'
   }
}

When I do a find (or findOne), I can do this..

db.company.findOne({name:'cnn'});

What if I want to search for the value in the 'contact'?

e.g. search for record with url='cnn.com'

or to find out which records has the key "url" in 'contact'

Upvotes: 1

Views: 1436

Answers (1)

Chris Heald
Chris Heald

Reputation: 62708

To search for a sub-key, you just give the path to the key delimited by periods.

db.company.findOne({"contact.url": "cnn.com"})

To find out which records have a contact URL:

db.company.findOne({"contact.url": {$ne: null}})

Note that these queries will be full collection scans unless you create an index for the subkey queried. Use judiciously.

Upvotes: 4

Related Questions