代码之家  ›  专栏  ›  技术社区  ›  Vadorequest

nodemongodbnative如何在子文档上创建索引?

  •  0
  • Vadorequest  · 技术社区  · 11 年前

    来自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 单元

    1 回复  |  直到 11 年前
        1
  •  4
  •   WiredPrairie    11 年前

    此代码在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"
        }
    ]