如何查询递归MongoDB Document [File System of files and folders].&l



我正在开发一个应用程序,该应用程序使用MongoDB (typegoose)来存储由文件和文件夹组成的类文件系统(递归)文档。但是,我不知道如何查询这样的模式。对于查询,提供了以下内容:

  1. 用户_id
  2. 按顺序排列的文件夹名称数组['root', 'nestedFolder1', 'nestedFolder2', '等…']
  3. 最后选择的文件夹的_id

模式如下

import { Types } from "mongoose";
interface File {
_id: Types.ObjectId;
fileName: string;
isDir: false;
content: string;
title: string;
description: string;
}
interface FileSystem {
_id: Types.ObjectId;
folderName: string;
isDir: true;
files: File[] | [];
folders: FileSystem[] | [];
}
interface Project {
_id: Types.ObjectId;
projectName: string;
fileSystem: FileSystem;
}
interface User {
_id: Types.ObjectId;
projects: Project[];
}

更新:这里有一个供参考的回复https://replit.com/@alphacoma18 mongodb-recursive-schema # server.ts

1-最简单的查询,获取所有文件系统文档:

const fileSystems = await FileSystem.find({
// Empty Object means no condition thus give me all your data
});

2-使用$eq运算符匹配具有特定值

的文档
const fileSystems = await FileSystem.find({
isDir: true,
folderName: { $eq: 'root' }
});

3-使用$in操作符将特定字段与可能值的数组进行匹配。

const fileSystems = await FileSystem.find({
isDir: true,
folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] }
});

4-使用$和操作符指定多个条件

const fileSystems = await FileSystem.find({
$and: [
{ isDir: true },
{ folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } }
]
});

5-检索所有非空的目录文档。

const fileSystems = await FileSystem.find({
isDir: true,
$or: [
{ files: { $exists: true, $ne: [] } },
{ folders: { $exists: true, $ne: [] } }
]
});

6-所有文件夹名称以字母"n"开头的目录

const fileSystems = await FileSystem.find({
isDir: true,
folderName: { $regex: '^n' }
});

现在更严格的查询:

1-计算文档总数

const count = await FileSystem.aggregate([
{ $count: 'total' }
]);

2-计算作为目录的文档总数

const count = await FileSystem.aggregate([
{ $match: { isDir: true } },
{ $count: 'total' }
]);

3-获取'文件夹名'和'文件名;

const fileSystems = await FileSystem.aggregate([
{ $match: { isDir: false } },
{ $project: { folderName: 1, fileName: 1 } }
]);

4-检索每个目录(isDir: true)中文件的总数(isDir: false)

const fileCounts = await FileSystem.aggregate([
{ $match: { isDir: true } },
{
$project: {
folderName: 1,
fileCount: {
$size: {
$filter: {
input: '$files',
as: 'file',
cond: { $eq: ['$$file.isDir', false] }
}
}
}
}
}
]);

5-递归结构查询:FileSystem接口是递归的,因为它有一个文件数组和一个文件夹数组,它们的类型都是File[]和FileSystem[]。

要查询这个递归模式,您可以在聚合管道中使用$lookup操作符,根据一些条件在FileSystem和它自己之间进行左连接。

//Retrieve All Documents from FileSystem and their child documents
const fileSystems = await FileSystem.aggregate([
{
$lookup: {
from: 'FileSystem',
localField: '_id',
foreignField: 'parentId',
as: 'children'
}
}
]);
//Use the match operator in the pipeline to filter the results: 
const fileSystems = await FileSystem.aggregate([
{
$lookup: {
from: 'FileSystem',
localField: '_id',
foreignField: 'parentId',
as: 'children'
}
},
{ $match: { isDir: true } }
]);

相关内容

最新更新