我有两个收藏书籍和作者。当我在这些集合之间进行查找时,我得到了所需的结果,但我需要将“_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"
}
]
}
作者的身份是“1”,而那应该是“10”。请建议我如何进行更改
您可以选择$unwind作者,项目ID,然后分组,或使用$map单独重塑作者。我相信后者应该表现得更好,但是当你硬编码作者的字段时,它的灵活性会有所提高:
Book.collection.aggregate([
{$addFields: {id:"$_id", "authors": {$map:{
input: "$authors",
as: "a",
in: {
"id": "$$a._id",
"first": "$$a.first",
"last": "$$a.last",
"book_id": "$$a.book_id",
"updated_at": "$$a.updated_at",
"created_at": "$$a.created_at"
}
}}}},
{$project: {_id:0}}
])
试试这个,只需放松并将这个$authors._id
放在项目管道中
Book.collection.aggregate([
{'$lookup' => {'from' => "authors",
'localField' => "_id",
'foreignField' => "book_id",
'as' => "authors"}},
{'$unwind' => '$authors'},
{'$project' => {'id' => '$authors._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}}}
])