我在本地工作 - 这永远不会在实时网站上完成。我构建了一个节点/快速服务器,它将接受 Mongo 的字符串化聚合管道,并将结果返回给浏览器:
app.get('/aggregate/:collection', function(req, res) {
var queryObject = JSON.parse(req.param('q'));
var recProvider = getProviderForTable(req.params.collection);
recProvider.getCollection(function(err, collection) {
collection.aggregate(queryObject, {}, function(err, data) {
res.json(data);
});
});
});
Run Code Online (Sandbox Code Playgroud)
这使得在我构建数据可视化的浏览器中进行一些快速查询变得很方便:
$.get(LOCAL_SERVER + '/aggregate/my_records?q=' + JSON.stringify(pipeline));
Run Code Online (Sandbox Code Playgroud)
我几乎开始构建像 Mongoose 那样的查询构建器,但只是为了构建聚合管道数组。我想知道我是否可以在浏览器中使用 Mongoose 的查询构建器来创建数组,然后使用它来访问我的快速服务器以获取数据,如上所述?
我想构建一个可链接的对象,例如...
pipeline()
.where('value').gt(1000)
.where('category').in([1, 2, 3])
.sort('-date')
.skip(100).limit(10);
Run Code Online (Sandbox Code Playgroud)
...将返回聚合管道:
[
{
$match: {
value: {
$gt: 1000
},
category: {
$in: [1, 2, 3]
}
}
},
{
$sort: {
date: -1
}
},
{
$skip: 100,
$limit: 10
}
]
Run Code Online (Sandbox Code Playgroud)
查看源代码,看起来每当您使用该aggregate()
函数时,管道都存储在名为 的属性中_pipeline
。
使用您的示例,如果您编写这样的聚合管道......
var myAggregation = Model // "Model" should actually be the name of your model
.aggregate()
.match({ value: { $gt: 1000 } })
.match({ category: { $in: [1, 2, 3] } })
.sort('-date')
.skip(100)
.limit(10);
Run Code Online (Sandbox Code Playgroud)
然后myAggregation._pipeline
就会像这样...
[ { '$match': { value: { $gt: 1000 } } },
{ '$match': { category: { $in: [1, 2, 3] } } },
{ '$sort': { date: -1 } },
{ '$skip': 100 },
{ '$limit': 10 } ]
Run Code Online (Sandbox Code Playgroud)
然而,我注意到您正在使用该where()
函数,它实际上创建了一个Query
in mongoose 而不是聚合管道。如果您选择使用where()
,则条件和选项的设置会略有不同。相反myAggregation._pipeline
,它们将被拆分为myAggregation._conditions
和myAggregation.options
。它们的编写方式并不完全相同,但也许您可以将其转换为您想要的格式。
归档时间: |
|
查看次数: |
2103 次 |
最近记录: |