Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lấy tất cả collection có tên chứa '2015' trong MongoDB

Tạo các collection mẫu:

> use web;
switched to db web
> db.createCollection("2015-myCollection"); { "ok": 1 }
> db.createCollection("2019-employeeCollection"); { "ok": 1 }
> db.createCollection("2015-yourCollection"); { "ok": 1 }

Hiển thị tất cả collection

> show collections;

Kết quả:

2015-myCollection  2015-yourCollection  2019-employeeCollection  applyConditionDemo  check  creatingAliasDemo  emp_info  emptyCollection  removeNullDemo

Lọc collection bắt đầu bằng "2015-"

> db.getCollectionNames().filter(function(v) { return /^2015\-/.test(v); })

Kết quả:

["2015-myCollection", "2015-yourCollection"]

Lọc collection bắt đầu bằng "2019-"

> db.getCollectionNames().filter(function(v) { return /^2019\-/.test(v); })

Kết quả:

["2019-employeeCollection"]

Giải thích: db.getCollectionNames() trả về mảng tên collection. .filter() là phương thức JavaScript mảng. Regex /^2015\-/ khớp chuỗi bắt đầu bằng "2015-".