c-chavez
c-chavez

Reputation: 7506

Nodejs Mongodb get first element of array using find without aggregate

I'm using Mongodb NodeJs driver to find a value in my db. The object structure of my collection is:

{
    '_id': ObjectId(),
    'name': ''
    'myList': []
}

I need to filter documents that have at least one element in the array and return the values including the list and (in a separate property) the first element of that list. I want to know if it is possible to do this without using an aggregate, but I haven't been able to return the first element of the list.

My code to find the values is:

let dbClient = await MongoClient.connect(myDbUrl, {useNewUrlParser: true});
let database = dbClient.db(myDatabase);

let query = {
    myList: {$exists: true, $not: {$size: 0}},
};

let options = {
    projection: {

    }
}

let result = await database.collection(myCollection).find(query, options).toArray();

dbClient.close();

I've omitted a try catch statement irrelevant to the situation.

So far I've tried (without success):

let options = {
   projection: {
        'myList.0': 1
    }
}

let options = {
   projection: {
        '$myList.0': 1
    }
}

let options = {
   projection: {
        firstElement: { 'myList.0': 1 }
    }
}

let options = {
    projection: {
        firstElement: {$arrayElemAt: ['$myList', 0]},
    }
}

let options = {
    $project: {firstElement: {$arrayElemAt: ['$myList', 0]}},
}

The errors I get with these are basically that the functions are not supported.

I know that using aggregate I can add this to the query pipeline to get the desired projection:

{$project: {firstElement: {$arrayElemAt: ['$myList', 0]}}},

Is it possible to get this value using find, or is it only possible with aggregate?

Version:

"mongodb": "3.1.6"

Upvotes: 1

Views: 1815

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

It's the positional $ operator that returns first element from the array. You projections must be something like

let options = {
   projection: {
        'myList.$': 1
    }
}

Upvotes: 2

Related Questions