user982853
user982853

Reputation: 2488

Mongodb - Find Embedded Array in PHP

I have a collection called Forms: Inside that collection i have a sub collect called Form_Fields. So a document may look like this:

}
   "_id": ObjectId("4f2984b1af06e80418000000"),
   "Form_Name": "Users",
   "Form_Fields": [
                  {"Field_Name": "First_Name"},
                  {"Field_Name": "Last_Name"}
                  ]
}

So how do i find the array for the form fields?

I have tried :

$collection->find(array("Form_Name"=>"Users");

but that does return the array

First_Name, Last_Name

What i am trying to accomplish is to perform a find that will locate the document with the Form_Name = Users and then return an array that contains all of the Form_Fields.

I know this isn't right but something like:

find(array("Form_Name=>"Users"(array(Form_Fields)))

and it return the array of only the 2 Field_Names?

Can someone help me to construct the "find" to find the 'Users" form elements in an array. so i want to find all the 'Form_Fields' inside the document with the 'Form_Name' = 'Users' document.

Thank you.

Update

I want to search an embedded doc with a particular parent document attribute. So lets say i have a collection "Forms" and embedded inside that collection i have a doc called "Form_Fields". So that each form has embedded/related fields. I wanted to find all embedded form fields for the doc with the attribute "Form_Name":"Users".

Should i perform an embedded search like:

$cursor = $collection->find(array("Form_Name"=>"Users"));

//this brings back the doc where form_name = users. //Should i then expand that search by using something like:

$cursor -> find("the search to find all embedded Form_Fields")

??

Upvotes: 0

Views: 971

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

You can specify what field from a document you want to fetch. Here's your example in javascript.

db.collection.find({"Form_Name": "Users"}, {"Form_Fields": 1});

This will return a document (or several) with two fields, _id and Form_Fields. If you don't want the _id, you have to specifically exclude it.

db.collection.find({"Form_Name": "Users"}, {"Form_Fields": 1, "_id": -1});

Upvotes: 1

Related Questions