How use position query with operator $first

The last question for today that I have been collecting for half a year)

My simple collection:

{
    _id: 1,
    books: [
         { bookId: 55, otherfields },
         { bookId: 66, otherfields },
    ]
}

How i can use position and $first both ?

c.findOne({_id: 1, 'books.bookId': 66}, { projection: {_id:0, book: { $first:'$books.$'} }});

get error :

MongoServerError: Unsupported projection option: book: { $first: “$books.$” }

c.findOne({_id: 1, 'books.bookId': 66}, { projection: {_id:0, book: { $first:'$books'} }});
get error:

MongoServerError: Unsupported projection option: book: { $first: "$books" }

I use latest mongodb and driver

@alexov_inbox ,

Its best to use aggregation for this kind of queries:

c.aggregate([{$match: {_id: 1, 'books.bookId': 66}}, {$project: {
 books: {
  $first: {
   $filter: {
    input: '$books',
    cond: {
     $eq: [
      '$$this.bookId',
      66
     ]
    }
   }
  }
 }
}}])
1 Like

Does the $first operator work only with aggregation?

$first is an aggregation operator yes.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.