node.js操作mongoDB数据库示例分享(2)


var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=mongo.Server(host,port,{auto_reconnect:true});
var db=new mongo.Db("node-mongo-examples",server,{safe:true});
db.open(function (err,db) {
    db.collection("users", function (err,collection) {
        if(err) throw err;
        else{
            collection.find({}).toArray(function(err,docs){
                if(err) throw  err;
                else{
                    console.log(docs);
                    db.close();
                }
            });
        }
    });
});

//带查询条件的搜索

复制代码 代码如下:


var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=mongo.Server(host,port,{auto_reconnect:true});
var db=new mongo.Db("node-mongo-examples",server,{safe:true});
db.open(function (err,db) {
    db.collection("users", function (err,collection) {
        if(err) throw err;
        else{
            collection.find({username:{$in:["延思","三"]}}).toArray(function(err,docs){
                if(err) throw  err;
                else{
                    console.log(docs);
                    db.close();
                }
            });
        }
    });
});

//插入一批数据,并且进行搜索type==food且price字段值小于10

复制代码 代码如下:


var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=mongo.Server(host,port,{auto_reconnect:true});
var db=new mongo.Db("node-mongo-examples",server,{safe:true});
var docs=[
    {type:"food",price:11},
    {type:"food",price:10},
    {type:"food",price:9},
    {type:"food",price:8},
    {type:"book",price:9}
];
db.open(function (err,db) {
    db.collection("goods", function (err,collection) {
        if(err) throw err;
        else{
            collection.insert(docs, function (err,docs) {
                if(err) throw  err;
                else{
                    collection.find({type:"food",price:{$lt:10}}).toArray(
                        function(err,docs){
                            if(err) throw err;
                            else{
                                console.log(docs);
                                db.close();
                            }
                        }
                    );
                }
            })
        }
    });
});

查询中的或的表达:

复制代码 代码如下:


collection.find({$or:[
    {type:"food"},
    {price:{$lt:10}}
  ]})

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgsyss.html