Node.js: Truy vấn dữ liệu trong bộ sưu tập (Query)


Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên

Lọc kết quả trả về có yêu cầu phù hợp

Khi tìm tài liệu trong một bộ sưu tập, bạn có thể lọc kết quả bằng cách sử dụng một đối tượng truy vấn.

const { MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
  var dbo = client.db("mydb");
 
var query = { address: "Highway 71" };
  dbo.collection("customers").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
   
client.close();
  });
});

 với Mongoose

const mongoose = require('mongoose');
const url = "mongodb://localhost:27017/mydb";
const schema = new mongoose.Schema({name: "string", address: "string"})
const userinfo = mongoose.model("userinfo", schema, "customers")

mongoose.connect(url, function(err) {
  if (err) throw err;
 
var query = { address: "Highway 71" };
  userinfo.find(query, function(err, result){
    if (err) throw err;
    console.log(result)
    mongoose.connection.close()
  })
});

Kết quả

[
  {
    _id: new ObjectId("630058ed81986da58fb01bbd"),
    name: 'John',
    address: 'Highway 71',
    __v: 0
  } 
]

Lọc kết quả trả về với biểu thức chính quy 

Để chỉ tìm các tài liệu có trường "address" bắt đầu bằng chữ "L", chúng ta có thể sử dụng biểu thức chính quy /^L/:

const MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
  var dbo = client.db("mydb");
  
var query = { address: /^L/ };
  dbo.collection("customers").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    
client.close();
  });
});

với Mongoose

const mongoose = require('mongoose');
const url = "mongodb://localhost:27017/mydb";
const schema = new mongoose.Schema({name: "string", address: "string"})
const userinfo = mongoose.model("userinfo", schema, "customers")

mongoose.connect(url, function(err) {
  if (err) throw err;

  var query = { address: /^L/ };
  userinfo.find(query, function(err, result){
    if (err) throw err;
    console.log(result)
    mongoose.connection.close()
  })
});

Kết quả

[
  {
    _id: new ObjectId("630058ed81986da58fb01bbe"),
    name: 'Peter',
    address: 'Lowstreet 4',
    __v: 0
  }

» Tiếp: Node.js và Raspberry Pi
« Trước: Tìm dữ liệu trong bộ sưu tập (FindOne và FindAll)
Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên
Copied !!!