使用$ project aggregation来编辑文档模式 - MongoDB

时间:2016-02-29 15:00:05

标签: mongodb

我有这个MongoDB文档:

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

使用$project(聚合运算符)我必须重构前一个模式以获取:

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

为了达到我的目标,我使用了以下聚合:

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

但是我收到了一个错误:

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

我不明白为什么聚合不起作用,因为如果我想重塑前一个模式来获取:

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

我可以使用这个聚合(并且它可以工作):

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

1 个答案:

答案 0 :(得分:1)

使用 $literal 运算符返回值而不进行解析。它用于聚合管道可以解释为表达式的值,就像您目前得到的错误一样:

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

示例输出

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