I'm using mongodb in a nodejs project, in which I have a collection of users :
{ "_id" : ObjectId("1"), "firstName": "John", "lastName" : "Doe", "age":20 }
{ "_id" : ObjectId("2"), "firstName": "Jane", "lastName" : "Doe", "age":22 }
{ "_id" : ObjectId("3"), "firstName": "Bob", "lastName" : "Smith","age": 32 }
{ "_id" : ObjectId("4"), "firstName": "John", "lastName" : "Smith","age":40}
{ "_id" : ObjectId("5"), "firstName": "John", "lastName" : "Deer","age":66}
I'd like a query to return an array of document ids matching the array of users by their first and last name ordered by the array I've given here
This is what I'm trying to fiddle with:
var usersToFind = [
{ firstName: "John", lastName: "Smith"},
{ firstName: "John", lastName:"Doe"}
];
db.collection('users').then(users => users.aggregate([
{ $match : { /* what to put here? */ } },
{ $addFields : { '__order' : { $indexOfArray : [usersToFind, /* Missing here something */} } },
{ $sort : { '__order' : 1 } }
]).toArray(results => {
console.log(results);
// Should print ["ObjectId(4)", "ObjectId(1)"];
});
I'm probably missing something fundamental about how to work with mongodb due to my limited knowledge of it.
I'd be grateful if you could help me solve the query or show me a better way to achieve it.
I could always iterate my usersToFind
array and find documents one by one, but I'd like to use a single query here. Another approach is to use $or
and $and
Thank you