Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB nested value query

Tags:

mongodb

I have an entry in my database that looks like:

{
  "_id" : ObjectId("4e93ace3f8208ca743000004"),
  "title" : "Entry",
  "domain" : {
    "_id" : ObjectId("4e9305d5f8208cab43000001"),
    "name" : "Google"
  }
}

To query for that particular entry (or entries that use the same domain) it looks like I'm supposed to query using:

db.entries.find({domain._id : ObjectId("4e9305d5f8208cab43000001")})

This however produces an error:

SyntaxError: missing : after property id (shell):1

What am I doing wrong in my query? Secondarily, how can I branch this out to PHP?

like image 294
Devin Rodriguez Avatar asked Oct 11 '11 22:10

Devin Rodriguez


People also ask

How do I query nested data in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

What is nested document in MongoDB?

MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document.

How do I query an array field in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

What is MongoDB elemMatch?

Definition. $elemMatch. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.


1 Answers

You will need to have the field name in quotes, eg:

db.entries.find({ "domain._id" : ... })
like image 152
Clinton Avatar answered Oct 16 '22 05:10

Clinton