MongoDB_索引

本文介绍如何使用Node.js连接MongoDB数据库并进行基本的数据查询及索引创建操作,包括建立连接、打开数据库、创建索引等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

'use strict';

// connect MongoDB
var mongodb = require("mongodb");
var server = new mongodb.Server("127.0.0.1", 27017, {auto_reconnect:true});
var client = new mongodb.Db("testDB", server, {w:1});

client.open(function(err, db){
    if (err)
    {
        throw err;
    }
    else
    {
        db.collection("testTable", {safe:true}, function(err, collection){
            if (err)
            {
                throw err;
            }
            else
            {
                // 全部查找
                collection.find().toArray(function(err, result){
                    //JsonLog(result);
                });

                // 创建单个索引 1表示对应键的索引按升序存储,-1表示对应键的索引按降序存储。
                //collection.ensureIndex({name:1}, {}, function(err, result){
                //    JsonLog(result);
                //});

                // 创建联合索引 1表示对应键的索引按升序存储,-1表示对应键的索引按降序存储。
                //collection.ensureIndex({name:1, age:-1}, {}, function(err, result){
                //    JsonLog(result);
                //});

                // 创建索引,并且指定名称
                //collection.ensureIndex({level:1}, {level:"x_level"}, function(err, result){
                //    JsonLog(result);
                //});

                // 创建唯一索引
                //collection.ensureIndex({name:1}, {unique:true}, function(err, result){
                //    JsonLog(result);
                //});

                // 查看表的对应字段索引
                //collection.indexInformation({age:1}, function(err, result){
                //    JsonLog(result);
                //});

                //// 删除表的对应字段索引
                //collection.dropIndex({name:1}, {}, function(err, result){
                //    JsonLog(result);
                //});
            }
        });
    }
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值