harry-potter
harry-potter

Reputation: 2049

Use $project aggregation to edit documents schema - MongoDB

I have this MongoDB document:

{
  "_id" : 1,
  title: "abc123",
  isbn: "0001122223334",
  author: { last: "zzz", first: "aaa" },
  copies: 5
}

Using $project (aggregation operator) I have to reshape the previous schema to get:

{
  "_id" : 1,
  field: {key:"title", value:"abc123"},
  isbn: "0001122223334",
  author: { last: "zzz", first: "aaa" },
  copies: 5
}

To reach my target I used the following aggregation:

db.book.aggregate([{$project: {"field": {"key":"title", "value":"$title"}}}])

but I got an error:

{
"ok" : 0,
"errmsg" : "FieldPath 'isbn' doesn't start with $",
"code" : 16873
} : aggregate failed

I don't understand why that aggregation does not work, since if I want to reshape the previous schema to get:

{
"_id" : 1,
"author" : {
    "last" : "zzz",
    "first" : "aaa"
     },
"copies" : 5,
 "fieldTitle" : {
      "key" : "abc123"
       }
}

I can use this aggregation (and it works):

db.book.aggregate([{$project: {_id:1, fieldTitle:{key:"$title"}, author:1, copies:1}}])

Upvotes: 1

Views: 145

Answers (1)

chridam
chridam

Reputation: 103335

Use the $literal operator to return a value without parsing. It's used for values that the aggregation pipeline may interpret as an expression, like the error you are presently getting:

db.book.aggregate([
    {
        $project: {
            "field.key": { "$literal": "title" }, 
            "field.value": "$title",
            "author": 1, "copies": 1            
        }
    }
])

Sample Output

{
    "result" : [ 
        {
            "_id" : 1,
            "author" : {
                "last" : "zzz",
                "first" : "aaa"
            },
            "copies" : 5,
            "field" : {
                "key" : "title",
                "value" : "abc123"
            }
        }
    ],
    "ok" : 1
}

Upvotes: 1

Related Questions