mongoDB クエリ入門編 #mongoDB
index:
概要:
noSQL型の、mongodb で
クエリのメモとなります。
node.js で monk で接続した場合の例も試してみました。
概要
mongo DB 2.4.14
mongo shell (mongo)
node.js 10.16.0
参考のファイル
mongo shell
・データの登録
Collection 作成、 insert
https://github.com/kuc-arc-f/mongo_1/blob/master/mongo_js/insert_book1.js
use db2; db.createCollection("books"); db.books.insert({"no" : 1, "title": "t1", "content" : "c1" }); db.books.insert({"no" : 2, "title": "t2", "content" : "c2" }); db.books.insert({"no" : 3, "title": "t3", "content" : "c3" }); db.books.find();
sort
項目を、指定して。sort 実行
1: 昇順
-1 : 降順
db.books.find().sort({no : -1}) { "_id" : ObjectId("5d3ba80d60a04da5623c0173"), "no" : 3, "title" : "t3", "content" : "c3" } { "_id" : ObjectId("5d3ba80c60a04da5623c0172"), "no" : 2, "title" : "t2", "content" : "c2" } { "_id" : ObjectId("5d3ba7ec60a04da5623c0171"), "no" : 1, "title" : "t1", "content" : "c1" }
比較, lt ,gt
・lt
小さい
> db.books.find( {"no": {$lt: 2}} ); { "_id" : ObjectId("5d3ba7ec60a04da5623c0171"), "no" : 1, "title" : "t1", "content" : "c1" }
・gt
大きい
db.books.find( {"no": {$gt: 2}} ); { "_id" : ObjectId("5d3ba80d60a04da5623c0173"), "no" : 3, "title" : "t3", "content" : "c3" }
・lte
以下
> db.books.find( {"no": {$lte: 2}} ); { "_id" : ObjectId("5d3ba7ec60a04da5623c0171"), "no" : 1, "title" : "t1", "content" : "c1" } { "_id" : ObjectId("5d3ba80c60a04da5623c0172"), "no" : 2, "title" : "t2", "content" : "c2" }
・gte
以上
> db.books.find( {"no": {$gte: 2}} ); { "_id" : ObjectId("5d3ba80c60a04da5623c0172"), "no" : 2, "title" : "t2", "content" : "c2" } { "_id" : ObjectId("5d3ba80d60a04da5623c0173"), "no" : 3, "title" : "t3", "content" : "c3" }
regex , 部分一致検索
データの登録
use db2; db.createCollection("tasks"); db.tasks.insert({"no" : 1, "title": "t1-title", "content" : "c1-conte" }); db.tasks.insert({"no" : 2, "title": "t2-title", "content" : "c2-conte" }); db.tasks.insert({"no" : 3, "title": "t3-title", "content" : "c3-conte" }); db.tasks.find();
db.tasks.find({"title": {"$regex": /tit/}}, { title: 1})
> db.tasks.find({"title": {"$regex": /tit/}}, { title: 1}); { "_id" : ObjectId("5d3bc27ca7ccfe2827b360cf"), "title" : "t1-title" } { "_id" : ObjectId("5d3bc27ca7ccfe2827b360d0"), "title" : "t2-title" } { "_id" : ObjectId("5d3bc27da7ccfe2827b360d1"), "title" : "t3-title" }
monk / node.js
・sort
https://github.com/kuc-arc-f/mongo_1/blob/master/find_sort.js
var collection = db.get('books'); collection.find({}, {sort: {no: -1}} ,function(e, docs){ console.log(docs); db.close() });
・比較
https://github.com/kuc-arc-f/mongo_1/blob/master/find_lt.js
var collection = db.get('books'); collection.find( {"no": {$lt: 2}},{},function(e, docs){ console.log(docs); db.close() });
・regex
https://github.com/kuc-arc-f/mongo_1/blob/master/find_regex.js
var collection = db.get('tasks'); collection.find({"title": {"$regex": /tit/ }}, {} ,function(e, docs){ // console.log(docs); var items = []; docs.forEach( function (item) { items.push(item); console.log(item.title ); }); db.close() });