0

I am new in nosql and I need a query that works like join. I hope you can help me with that. User collection which has id name Idea collection which includes id comment user_id

one can have many comments and I would like to reach the comments given by user Idea.comment User.name is the result I want I hope you can help me thx

db.ProjectIdea.aggregate([
    {
    $lookup:{
        from:"User",
        localField:"createdUser",
        foreignField:"_id",
        as:"kim"
    }
}
]).forEach(
function(u){

         print(u.kim[0].name;
    }
);

however, some users do not have name attribute defined so i am havin error How do I perform the SQL Join equivalent in MongoDB? i tried the thing in the link before but could not solve the whole problem

alkanschtein
  • 305
  • 1
  • 13
  • 2
    Possible duplicate of [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) – Neodan Dec 06 '17 at 12:27
  • yes it is similar but not the same issue – alkanschtein Dec 07 '17 at 13:37

1 Answers1

0

I found the solution

db.ProjectIdea.aggregate([
    { "$match": { projectId:ObjectId("59e72193212ef231dc5c7d7d") } },
    {
        $lookup:{
            from:"User",
            localField:"createdUser",
            foreignField:"_id",
            as:"kim"
    }
}
]).forEach(
    function(u){
        print(""+u._id+'|'+u.caption.replace("\r"," ").replace("\n"," 
        ")+'|'+u.idea.replace("\r"," ").replace("\n"," ")+'|'+u.kim[0].name+' 
'+u.kim[0].lastName+"");
}
);

Only problem here is if the "kim" part does not have the name and lastName (eg after the comment deleting the person who gives the comment can make that part undefined) this code throws error. I will try to fix that error too. Then edit that part again.

alkanschtein
  • 305
  • 1
  • 13