2
votes

Suppose this document:

{
    _id : Object(“12918”),
    username : “username”,
    password : “password”,
    occupation: {
        name : “Football”,
        code : 254,
    }
},
{
    _id : Object(“12919”),
    username : “username2”,
    password : “password2”,
    occupation: {
        name : “Basketball”,
        code : 255,
    }
}

I want a query that returns:

{
    _id : Object(“12918”),
    occupation : {
        name : “*”,
        code : 254
    }
},
{
    _id : Object(“12919”),
    occupation : {
        name : “*”,
        code : 255
    }
}

So, a query that just returns the fields _id and occupation. And the field occupation.name must be replaced by * in all records.

I tried this query:

aggregate([
    {
        "$project" : 
        { 
            "_id" : 1, 
            “occupation" : 1,
            “occupation.name" : { $literal:“*” } 
        } 
    }
])

which returned the following exception:

{ "ok" : 0, "errmsg" : "can't add an expression for field occupation because there is already an expression for that field or one of its sub-fields.", "code" : 16400 }

Is there a way to achieve this?

2
What is your mongo server version ?s7vr
It's version 3.0.1José Miguel Melo

2 Answers

2
votes

You can specify the nested document projection of occupation like this :

db.test.aggregate([{
    "$project": {
        "_id": 1,
        "occupation": {
            code: 1,
            name: { $literal: "*" }
        }
    }
}])
1
votes

You can do it like this :

db.collectionName.aggregate([{$project:{
           _id:1,
           occupation:{"name":{$literal:"*"},
                       "code":"$occupation.code"
                      } 
           }    
   }])