4

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 ? Commented Feb 22, 2017 at 18:21
  • It's version 3.0.1 Commented Feb 22, 2017 at 18:25

2 Answers 2

3

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

db.test.aggregate([{
    "$project": {
        "_id": 1,
        "occupation": {
            code: 1,
            name: { $literal: "*" }
        }
    }
}])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Bertrand!
but how too using 0 or 1 value replace with other value because when using 0 or 1 value using for hide and show key but how to using 0 or 1 value for replace previous value
2

You can do it like this :

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

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.