'How to list all indexes of Mongo Collection with MongoDB Node native?

Well I wanna know how I can fetch all indexes from a specific collection of mongodb. I trying with listIndexes, indexes and indexInformation, but these methods only give me empty values(array and object), but if I execute db.getCollection('truck').getIndexes() on mongo terminal, this give me all indexes.

I think maybe this is a bug, but I don't find any information about this, so let me show my examples and a screenshot from "Robo 3T".

await connection.collection('truck').indexes() // returns []
await connection.collection('truck').listIndexes().toArray() // returns []
await connection.collection('truck').indexInformation() // returns {}

enter image description here

So... Whats happend here? why these methods not working well?

Thanks :D

P.S: I'm using mongodb version 3.5.5: https://github.com/mongodb/node-mongodb-native



Solution 1:[1]

Looks like in the code await connection.collection('truck').indexes() you need to specify the database also. It is not clear what is connection.

The following script will print the indexes in the specified database and collection.

const MongoClient = require('mongodb').MongoClient;

( async function() {
     const client = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true } );
     try {
        await client.connect();
        const coll = client.db('test').collection('books');
        const indxs = await coll.indexes();
        console.log(indxs);     // prints all the indexes
     } catch (err) {
         console.log(err.stack);
     }
     client.close();
)();

Solution 2:[2]

listIndexes is a database command, you have to call it like this:

db.runCommand( {listIndexes: "truck"} )

or using the shorthand

db.truck.getIndexes()
db.collection('truck').getIndexes()

Method indexInformation does not exist in MongoDB (at least I did not find it). collection.indexes() I did not find either.

Solution 3:[3]

...for prettier output:

for ( var i=0; i < indxs.length; i++ ) {
    console.log(indxs[i].ns + '.' + indxs[i].name,'key(s):-\n',indxs[i].key);
}

Solution 4:[4]

Working Example in Nodejs with indexes()

a) Definition

export function getIndexes(coll, callback: Function) {
MongoClient.connect(process.env.uri, (err, db) => {
    db.db(dbWeb).collection(coll).indexes( (err, res) => {
        callback(res)
        db.close();
    })
})

}

b) Call

export function getIndexes(coll) { mongo[arguments.callee.name](coll, res => { console.log(res) }) }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prasad_
Solution 2 Wernfried Domscheit
Solution 3 Donald W Garton
Solution 4 Timo