MongoDB 3.2.6:$lookup和$project使用Mongoid重命名_id字段



我有两个收藏书和作者。当我在这些集合之间进行查找时,我得到了所需的结果,但我需要将"_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"。请建议我需要如何进行更改

试试这个,只需放松并在项目管道中给出这个$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}}}
  ])

您可以$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}}
])

最新更新