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?
You can specify the nested document projection of occupation
like this :
db.test.aggregate([{
"$project": {
"_id": 1,
"occupation": {
code: 1,
name: { $literal: "*" }
}
}
}])
You can do it like this :
db.collectionName.aggregate([{$project:{
_id:1,
occupation:{"name":{$literal:"*"},
"code":"$occupation.code"
}
}
}])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.