DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

Mongodb multiple indices per field

To enable unique index in node I do:

City.native(function(err, collection) {
    collection.ensureIndex({
        'name': 1,
    }, function(err, result) {
        //nothing
    });
});

But I would like to enable text index on name also. So after doing the above I do:

City.native(function(err, collection) {
    collection.ensureIndex({
        'name': 'text'
    }, function(err, result) {
        //nothing
    });
});

This perfectly creates both indices. My question is, is there any chance to merge this code?? I tried with

City.native(function(err, collection) {
    collection.ensureIndex({
        'name': 1,
        'name': 'text'
    }, function(err, result) {
        //nothing
    });
});

but this creates just the text index.

Upvotes: 0

Views: 37

Answers (1)

vmr
vmr

Reputation: 1935

To enable unique index in node you need to do :

City.native(function(err, collection) {
    collection.ensureIndex(
        {'name': 1},
        {unique:true}, 
        function(err, result) {
        //nothing
    });
});

Now to merge this code:(If no-ordering is specified for index then it is ascending order)

City.native(function(err, collection) {
    collection.ensureIndex(
        {'name': 'text'},
        {unique:true},
        function(err, result) {
        //nothing
    });
});

Upvotes: 1

Related Questions