【发布时间】:2018-08-10 13:06:28
【问题描述】:
我有两个收藏书籍和作者。当我在这些集合之间进行查找时,我得到了想要的结果,但我需要将“_id”重命名为“id”。当我重命名这些字段时,作者“_id”被替换为书籍“_id”而不是作者“_id”。请看下文
Book.collection.aggregate([
{'$lookup' => {'from' => "authors",'
localField' => "_id",
'foreignField' => "book_id",
'as' => "authors"}}
])
结果:
{
"_id": 1,
"title": "abc123",
"isbn": "0001122223334",
"copies": 5,
"updated_at": "2018-03-02T09:17:24.546Z",
"created_at": "2018-03-02T09:17:24.546Z",
"authors": [
{
"_id": 10,
"first": "a",
"last": "a",
"book_id": 1,
"updated_at": "2018-03-02T09:22:07.115Z",
"created_at": "2018-03-02T09:22:07.115Z"
}
]
}
我已尝试将 _id 字段重命名为 id
Book.collection.aggregate([
{'$lookup' => {'from' => "authors",
'localField' => "_id",
'foreignField' => "book_id",
'as' => "authors"}},
{'$project' => {'id' => '$_id', '_id' => 0, 'title' => 1, "isbn" => 1, "copies" => 1, "updated_at" => 1,
"authors" => { 'id' => '$_id', 'first' => 1, 'last' => 1, 'book_id' => 1, 'updated_at' => 1}}}
])
如果我说在上面的“项目”中
"authors" => { 'id' => '$_id'
那么结果就是
{
"id": 1,
"title": "abc123",
"isbn": "0001122223334",
"copies": 5,
"updated_at": "2018-03-02T09:17:24.546Z",
"created_at": "2018-03-02T09:17:24.546Z",
"authors": [
{
"id": 1,
"first": "a",
"last": "a",
"book_id": 1,
"updated_at": "2018-03-02T09:22:07.115Z",
"created_at": "2018-03-02T09:22:07.115Z"
}
]
}
作者的 id 是“1”,而应该是“10”。 请建议我需要如何进行更改
【问题讨论】:
标签: mongodb aggregation-framework