Created
June 16, 2023 18:52
-
-
Save sayhicoelho/c1ca40e3e3ec2b797d37b7bf8f3faad2 to your computer and use it in GitHub Desktop.
Find document index/position with MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function findDocumentIndex({ _id, collection, conditions, sort }) => { | |
const data = await db.collection(collection).aggregate([{ | |
$match: conditions | |
}, { | |
$sort: sort | |
}, { | |
$group: { | |
_id: null, | |
positions: { | |
$push: "$_id" | |
} | |
} | |
}, { | |
$project: { | |
position: { | |
$indexOfArray: ["$positions", _id] | |
} | |
} | |
}]).toArray() | |
if (data.length > 0) { | |
const { position } = data[0] | |
return position | |
} else { | |
throw new Error('Invalid query') | |
} | |
} | |
// Usage | |
const position = await findDocumentIndex({ | |
_id: new ObjectId(userId), | |
collection: 'users', | |
conditions: { | |
score: { | |
$ne: 0 | |
} | |
}, | |
sort: { | |
score: -1 | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment