0

My aim is to create inner array to main array when search for userid as 1 Below is my data

{ "_id" : 2,
  "name" : "test1", 
  "data" :[{"_id" : "1","file" : "nic", "userid" : [1,2 ]},
           {"_id" : "2","file" : "nic1","userid" : [1 ]  },
           {"_id" : 3,"file" : "nick2","userid" : [1,2 ]} 
 ]},

{ "_id" : 3,
  "name" : "test2",
  "data" : [{"_id" : "1","file" : "nic","userid" : [1,2 ]  },
            {"_id" : "2","file" : "nic1", "userid" : [3,2 ] } 
  ]}

need to get out put as

{"_id" : 1,"file" : "nic", "userid" : [1,2 ],"main_name" : "test1","main_id" : 2},
{"_id" : 2,"file" : "nic1","userid" : [1 ] ,"main_name" : "test1","main_id" : 2 },
{"_id" : 3,"file" : "nick2","userid" : [1,2 ],"main_name" : "test2","main_id" : 3},
{"_id" : 1,"file" : "nic","userid" : [1,2 ] ,"main_name" : "test2" ,"main_id" : 3}
1
  • 1
    What's the question again? Commented Oct 15, 2015 at 10:57

1 Answer 1

1

Basically the same answer to your last question, but without the $group to reconstruct the array and use a $project instead to restructure the document from the already de-normalized array elements.

$collection->aggregate(array(
    array( '$match' => array( "data.userid" => 1 )),
    array( '$unwind' => '$data' ),
    array( '$match' => array( 'data.userid' => 1 )),
    array(
        '$project' => array(
            '_id' => '$data._id',
            'nic' => '$data.nic',
            'user_id' => '$data.user_id',
            'main_name' => '$name',
            'main_id' => '$_id'
        )
    )
))
Sign up to request clarification or add additional context in comments.

2 Comments

same thing if i want to get all records irrespective of userid.how can we do that
@sasikanth Well "same thing" if you have other questions then Ask Another Question ( which is how it works here as this is not a discussion board or forum, but a Question and Answer resource, so you need to ask a singular clear question ). As well it is not clear what you are asking without that, as mostly your whole point so far is all about "filtering" the results by that said "userid" value. So why not just remove the $match statements if you just want everything? Or ask another question instead. That is what questions are for,

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.