0

Let's say I have some mongo DB query which returns following two documents. (I am using aggregation & projection which returns me this result set).

{
    "name" : {
        "value" : "ANDERSON"
    },
    "ID" : {
        "value" : "2356"
    },
}

{
    "employeename" : {
        "value" : "DAVID"
    },
    "ID" : {
        "value" : "2356"
    },
}

My DB is schema less & I am storing attributes and there values. There are multiple attributes which represents the same information. For e.g. here "name" & "employeename" represents the same thing. I want the final output in some common attribute (say "Employee Name"). This common attribute can have value either from "name" or "employeename".

I think this problem can be solved by adding one more pipe in with the aggregation. I tried $or (it returns true/false not the value)

db.getCollection('mycollection').aggregate([
    { "$project" : { 
        "name" : 1, 
        "ID" : 1, "employeename" : 1 
    }},
    { "$project":{
        "Employee Name": {$or : ["$name", "$employeename"]}
    }} 
])

Final Output should be

{
    " Employee Name" : {
        "value" : "ANDERSON"
    },
    "ID" : {
        "value" : "2356"
    },
}

{
    " Employee Name" : {
        "value" : "DAVID"
    },
    "ID" : {
        "value" : "2356"
    },
}

Can somebody tell me how to write this mongo DB command?

1 Answer 1

2

What you want is the $ifNull operator, you can also shorten your pipeline to one $project stage.

db.getCollection('mycollection').aggregate([
    { "$project" : { 
        "EmployeeName" : { "$ifNull": [ "$name",  "$employeename" ] },
        "ID" : 1,
    }}
])
Sign up to request clarification or add additional context in comments.

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.