1

I tried to map two collections its working fine but I have doubt in how to rename the column name using mongodb.

promotion collection

{ 
    "_id" : ObjectId("5cf7679a0b0bed2e7483b998"),   
    "group_name" : "Latest",   
    "products" : 
   [ObjectId("5cecc161e8c1e73478956333"),ObjectId("5cecc161e8c1e73478956334")]
}  

product collection

{ 
    "_id" : ObjectId("5cecc161e8c1e73478956333"), 
    "product_name" : "bourbon"
},
{ 
    "_id" : ObjectId("5cecc161e8c1e73478956334"), 
    "product_name" : "bour"
}

mapping query

db.promotional.aggregate(
     [
        {
           $lookup: {
             from: "product",
             localField: "products",
             foreignField: "_id",
             as: "products"
                   }
        },  
        {
           $project :{products :{_id:0}}  
        }

     ]
) 

I got output

{ 
    "_id" : ObjectId("5cf7679a0b0bed2e7483b998"),   
    "group_name" : "Latest",   
    "products" : 
     [
       {  
         "product_name" : "bourbon"
       },
       {  
       "product_name" : "bour"
       }
     ]
}

Expected output

{ 
    "_id" : ObjectId("5cf7679a0b0bed2e7483b998"),   
    "group_name" : "Latest",   
    "products" : 
     [
       {  
         "name" : "bourbon"
       },
       {  
       "name" : "bour"
       }
     ]
}

How to rename productname to name using mongodb

1 Answer 1

1

You can $map over the products array and can change the fields name

db.promotional.aggregate([
  { "$lookup": {
    "from": "product",
    "localField": "products",
    "foreignField": "_id",
    "as": "products"
  }},
  { "$addFields": {
    "products": {
      "$map": {
        "input": "products",
        "as": "product",
        "in": {
          "name": "$$product.product_name"
        }
      }
    }
  }}
])

If you are using mongodb version 3.6 and above

db.promotional.aggregate([
  { "$lookup": {
    "from": "product",
    "let": { "products": "$products" },
    "pipeline": [
      { "$match": { "$expr": { "$in": [ "$_id", "$$products" ] } } },
      { "$project": { "name": "$product_name", "_id": 0 }}
    ],
    "as": "products"
  }}
])
Sign up to request clarification or add additional context in comments.

3 Comments

@Fanpark I want rename function using in within {$project:{products :{"$name":product_name}}} its working or not
@HariSmith If it works then I would have probably answered that way. But it does not. It is an object structure {products :{"$name":product_name}} You cannot add key inside array with that.
thank you its working fine.can you explain how its work

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.