I have a nested Document which have some language dependent content and I want to search if content have data for specific language and query should return me content else false.
I tried this query option
$data = $collection->findOne(array('original'=>'What is this', 'translation.language'=>'english') );
I am expecting this result:
{
"language": "english",
"quote": "What is this"
}
but above query return both language content. Can anyone please share some code also regarding saving and updating data using PHP
My collection:
{
"_id": ObjectId("56a8844bc56760810e483815"),
"language": "english",
"original_key": "What is this",
"translation": [
{
"language": "english",
"quote": "What is this"
},
{
"language": "spanish",
"quote": "What is this Spanish"
}
]
}
Use the positional $
operator in the projection document of the findOne()
method when you only need one particular array element in selected documents:
// search criteria for nested array
$query = array(
'original' => 'What is this',
'translation.language' => 'english'
);
// projection (fields to include)
$projection = array('_id' => false, 'translation.$' => true);
$result = $collection->findOne($query, $projection);
$data = $result->translation;
var_dump($data);
I think you should use mongodb's aggregation pipeline.
This may work. Not tested.
db.collection.aggregate([
{$unwind :translation},
{$project: {original_key:true,language:true, quote:true}},
{$match:{original_key:"What is this", language:"english"}}
]);