Open fyn-dev opened 6 years ago
The aggregation framework is probably more suited to a search query, bit of my own example below in a repository pattern. The allowDiskUse
is for a large query, you may not need it.
@injectable()
export class NaRecordRepository implements NaRecordRepository {
public async search(query: any): Promise<any> {
const queryResult = await naRecordsDb.connect().then(() => naRecordsDb.NaRecords.aggregate([
{
$match: {
$text: {
$search: query.term
},
date: {
$gte: new Date(query.startDate),
$lt: new Date(query.endDate)
},
indexId: { $in: query.indexes },
docType: { $in: query.docTypes },
restrictIndex: false,
restrictImage: { $in: query.includeRestrictedImages },
indexedFlag: { $in: query.includePartialIndex }
}
},
{
$sort: {
date: query.dateSort,
}
},
{
$project: {
nameSSN: 0,
nameCode: 0,
firstName: 0,
middleName: 0,
lastName: 0,
nameDescription: 0,
nameIndirect: 0,
nameClass: 0,
inputId: 0,
changeId: 0
}
}
], {
allowDiskUse: true
}));
return queryResult;
}
But the query you are showing, would be something like this...
public async findNaRec(rec: NaRecordDTO): Promise<NaRecordDTO[]> {
const naRecval = await naRecordsDb.connect().then(() => naRecordsDb.NaRecords.find({lastName: rec.lastName}, {_id: 0})).then(val => {
return val.toArray();
});
return naRecval;
}
Thanks @Kaffiend - the aggregation pipeline is certainly a very powerful tool and well suited to these types of complex projection.
Additionally, if you simply want to provide a basic projection for a standard find
query (as you would on the MongoDB CLI) then you can leverage the find(conditions, fields)
overload of the Model.find
method.
So let's say you have the following document in MongoDB:
{
field: "value",
array: [
1,
2,
3,
4
]
}
Running myModel.find({ field: "value" }, { array: { $slice: 2 } }).toArray()
will resolve (it's a Promise
) to the following:
[
{
_id: ".....",
field: "value",
array: [1,2]
}
]
I hope that helps you @fyn-dev - but please let me know if you run into any issues with it.
I don't how such query in Iridium will work
.find( { field: value }, { array: {$slice: count } } )
I don't see any support for projection. How to use?