【问题标题】:node-mongodb-native how to create index on sub document?node-mongodb-native 如何在子文档上创建索引?
【发布时间】:2014-02-09 00:49:42
【问题描述】:

来自 mongodb 文档:

http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=ensureIndex#ensureIndex

基本上为子文档创建索引包括编写类似"address.city" 到目前为止,我还不能这样做。

我试过了:

index = "category.code";
index = { "category.code": 1 };
index = { "category": {code: 1} };

collection.ensureIndex( index, {unique: true, w: 1}, function(error, data){
        console.log(error ? error : documentName + ': [ensureIndex] ' + JSON.stringify(data));
    });

但没有创建索引。

还有其他解决办法吗? 当我通过mongo 从命令行执行此操作时,它可以工作。

db.type.ensureIndex({'category.code':1})

但是当我从 JS 脚本运行它时,它不会。

var mongodb = require('mongodb');

exports.up = function(db, next){
    var documentName = 'type';
    var collection = mongodb.Collection(db, documentName);
    ...

我正在使用https://npmjs.org/package/mongo-migrate 模块。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    此代码在 NodeJS 中按预期工作:

    var MongoClient = require('mongodb').MongoClient;
    
    MongoClient.connect("mongodb://localhost:27017/test", function (err, db) {
        db.collection("test").ensureIndex({ "category.code": 1 }, 
            function(err, result) {        
                db.close();
        });
    });
    

    显示集合的索引:

    运行代码之前

    > use test
    switched to db test
    > db.test.getIndexes()
    [
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.test",
                "name" : "_id_"
        }
    ]
    

    运行代码后

    > db.test.getIndexes()
    [
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.test",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "category.code" : 1
                },
                "ns" : "test.test",
                "name" : "category.code_1"
        }
    ]
    

    【讨论】:

    • 所以,我认为这是我正在使用的模块的问题,因为我没有看到任何其他解释。连接是从它打开的,但是代码是一样的,所以我不明白为什么它不起作用。
    • 你如何验证索引没有被创建?
    • 我使用 Genghis,它显示每个“表”的所有索引。我现在刚刚运行db.type.getIndexes() 也在命令行中检查,它是一样的。
    • 您指出的来源几乎没有任何内容...您确定它在正确的数据库中工作吗?默认为host: 'localhost', db: 'my-app', port: 27017
    • node node_modules/mongo-migrate -cfg config/custom/mongodb.json -dbn development-migrate -runmm 是我使用的命令行。其他索引和数据已正确插入数据库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多