如何使用MongoDB Node原生方法列出Mongo集合的所有索引?

3
我想知道如何从MongoDB的特定集合中获取所有索引。我尝试使用listIndexes、indexes和indexInformation等方法,但这些方法只返回空值(数组和对象)。但是如果在Mongo终端上执行db.getCollection('truck').getIndexes(),则可以返回所有索引。 我认为可能是个bug,但我没有找到任何相关信息,所以让我展示一下我的例子和“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

那么...发生了什么事情?为什么这些方法不能很好地工作?

谢谢 :D

P.S: 我正在使用mongodb版本3.5.5https://github.com/mongodb/node-mongodb-native

5个回答

7

看起来在代码 await connection.collection('truck').indexes() 中需要指定数据库。不清楚 connection 是什么。

以下脚本将打印指定数据库和集合的索引。

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();
)();

但是我已经指定了数据库...问题不在于数据库 :'( - Jorge Olaf
什么是问题? - prasad_
我认为问题出在驱动程序上,因为我尝试了Python和Node.js,但是都没有成功。经过尝试其他方法,我找到了解决方案:使用“command”。展示我的答案 :D - Jorge Olaf

2

好的,尝试了一些解决方法,比如将语言从 JavaScript 转换为 Python 并使用 Pymongo,但结果相同。最终决定使用命令行界面并使用驱动程序中的本机 API。

是的,我使用了 command,让我给你展示如何使用:

import {MongoClient} from 'mongodb'
const client = await MongoClient.connect("...")
const db = client.db("MyOwnDatabase")

// the next line retrieve empty array
db.collection('truck').indexes();

// the next line retrieve all indexes 
db.command({listIndexes: "truck"}).cursor.firstBatch;

在Python中这太相似了:
import pymongo
client = pymongo.MongoClient("...")
db = client.MyOwnDatabase

# retrieve empty object
db.truck.index_information()

# retrieve all indexes 
db.command("listIndexes", "truck") 

我认为这个问题与驱动程序有关...两个都是正式驱动,但都不能很好地工作:D

附言:我知道这个问题是关于 javascript 的,但我在 Python 中找到了相同的问题,并且这是两者的解决方案。


db.truck.indexes();truck是什么? - prasad_
truck is the collection. I lost collection(...) - Jorge Olaf

1

listIndexes是一个数据库命令,你需要这样调用它:

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

或者使用速记法
db.truck.getIndexes()
db.collection('truck').getIndexes()

indexInformation 方法在 MongoDB 中不存在(至少我没有找到)。collection.indexes() 也没有找到。


我认为您可能需要阅读问题和我的答案。谢谢。 - Jorge Olaf

1
"

...为了更美观的输出:

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

这里缺少一个完整的示例。 - Timo

0

使用Nodejs和indexes()的工作示例

a)定义

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) 调用

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接