不BB直接上代碼
// 導入mongodb
const mongoose = require("mongoose");
// 鏈接數(shù)據(jù)庫
mongoose.connect("mongodb://localhost/playground", { useNewUrlParser: true })
.then(() => console.log("飛起來了"))
.catch((err) => console.log(err, "錯了"));
// 接下來 創(chuàng)建集合規(guī)則
const courseScheme = new mongoose.Schema({
name: String,
author: String,
isPublish: Boolean,
age: Number,
});
// 重點來了
const Data = mongoose.model("Data", courseScheme);
// find sort讓數(shù)據(jù)進行排序 ('age') 我這寫的是年齡的字段 我是通過年齡來排序的
Data.find().sort("age").then((res) => {console.log(res)});
// ("age") 前邊加-號是讓查詢結果為降序
Data.find().sort("-age").then((res) => {console.log(res)});
// skip跳過多少條數(shù)據(jù) limit限制查詢數(shù)量(limit)可以用來作分頁查詢
Data.find().skip(2).limit(5).then((res) => {console.log(res)});
// 匹配年齡大于20 小于50的 $gt表示大于 $it表示小于
Data.find({age:{$gt:20,$lt:50}) => {console.log(res)});
// 匹配含有“敲代碼”的字段 $in
Data.find(name:{$in:['敲代碼'}).then((res) => {console.log(res)});
// 選擇要查詢的字段 seleat()
Data.find().seleat('name age).then((res) => {console.log(res)});