2

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"
    }
  ]
}   

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked :). Can you also share some code to insert new language data to existing collection ex. inserting Arabic language sub-document into exiting record?
0

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"}}
]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.