Skip to content

Instantly share code, notes, and snippets.

@sayhicoelho
Created June 16, 2023 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sayhicoelho/c1ca40e3e3ec2b797d37b7bf8f3faad2 to your computer and use it in GitHub Desktop.
Save sayhicoelho/c1ca40e3e3ec2b797d37b7bf8f3faad2 to your computer and use it in GitHub Desktop.
Find document index/position with MongoDB
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