Mongodb group by lookuped field makes an array

Viewed 53

DB example:

db.books.find()

[{ _id: ObjectId("b1"), author: ObjectId("a1"), name: "Fight Club" }]

db.author.find()

[{ _id: ObjectId("a1"), name: "Chuck Palahniuk" }]

When I'm trying to use aggregation framework and populate books with authors the populated field converts to array with single element. Here's my attempt:

db.books.aggregate([ 
  {$lookup: 
     { from: "authors", 
       localField: "author", 
       foreignField: "_id", 
       as: "author"
     } 
  } 
])

This gives me next structure:

[{ 
  _id: ObjectId("b1"), 
  name: "Fight Club", 
  author: [{ _id: ObjectId("a1"), name: "Chuck Palahniuk" }] // why an array?
}, ...]

What I need is simply author: { _id, name}. I Know how to get this with arrayElemAt, but this approach looks strange

0 Answers
Related