1. 程式人生 > 實用技巧 >MongoDB基本語句操作

MongoDB基本語句操作

//建立集合(第二個引數為可選項)
db.createCollection("表名",{ capped : true, autoIndexId : true, size : 6142800, max : 10000 });
   *** capped ---- 固定集合是指有著固定大小的集合,當達到最大值時,它會自動覆蓋最早的文件。當該值為 true 時,必須指定 size 引數。
*** autoIndexId ----- 3.2 之後不再支援該引數。(可選)如為 true,自動在 _id 欄位建立索引。預設為 false。
*** size ---- (可選)為固定集合指定一個最大值,即位元組數。
*** max ---- (可選)指定固定集合中包含文件的最大數量。
//刪除集合
db.getCollection("表名").drop();
//插入文件
db.getCollection("表名").insertOne({"a":3});
db.getCollection("表名").insertMany([{"b":3},{"c":4}]);
db.getCollection("表名").insert({
title: 'MongoDB 教程',description: 'MongoDB 是一個 Nosql 資料庫'});
db.getCollection("表名").save({title: 'MongoDB 教程',description: 'MongoDB 是一個 Nosql 資料庫'});
//save:如果 _id 主鍵存在則更新資料,如果不存在就插入資料。該方法新版本中已廢棄,可以使用db.collection.insertOne()
db.collection.replaceOne()來代替。
//更新文件
db.getCollection("表名").update(
{ "count" : { $gt : 3 } } , { $set : { "test2" : "OK"},false,true);
***第一個引數是查詢條件;第二個引數是要更新的結果;第三個引數是不存在可以插入,預設為false,不插入(可選);第四個引數是更新多條,為false只更新第一條匹配結果預設為false(可選);
//刪除文件
db.getCollection("表名").remove({"title":"MongoDB教程"});
//查詢文件
db.getCollection("表名").find({'tg':'TG378',date : {$lt :1608047999, $gt : 1607961600},TAG:{$in:["c1_b10_ep","c1_b11_ep"]}});//多條件查詢
//條件操作符
https://www.cnblogs.com/ExMan/p/9553553.html(這裡講解的比較詳細)
常用的一些:$gt(大於)、$lt(小於)、$gte(大於等於)、$lte(小於等於)、$in(值在陣列中)、$or(或者)、$and(和)
//limit與skip方法
db.getCollection.find().limit(2);
db.getCollection.find().limit(1).skip(1);//只會顯示第二條資料,跳過第一條資料了