【问题标题】:Mongoose: Apply function on schema field in query conditionMongoose:在查询条件中的模式字段上应用函数
【发布时间】:2012-11-19 22:26:42
【问题描述】:

在 MySQL 中,可以在 where 子句中的字段上应用本机函数。例如。

SELECT * FROM t WHERE DATE(the_date) < '2012-11-19';

SELECT * FROM t WHERE a+b < 20;

现在,是否可以在猫鼬查询的条件字段上使用函数?假设我正在查询这样的内容:

tSchema.find({a+b: {$lt: 20}}, callback);

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    不,您不能使用find 创建计算列,因此您必须使用aggregate,这样更灵活,但也更慢。

    像这样:

    tSchema.aggregate([
    
        // Include the a, b, and a+b fields from each doc
        { $project: {
            a: 1,
            b: 1,
            sum: {$add: ['$a', '$b']}}},
    
        // Filter the docs to just those where sum < 20
        { $match: {sum: {$lt: 20}}}
    
    ], function(err, result) {
        console.log(result);
    });
    

    为了完整起见,我应该注意,您可以使用 find$where 过滤器来执行此操作,但其性能很差,因此不推荐。像这样:

    tSchema.find({$where: 'this.a + this.b < 20'}, function(err, result) {
        console.log(result);
    });
    

    【讨论】:

    • 如果我不想从现有的两个列中获取列,但想应用 a+1 之类的简单函数或在字段上调用 ​​JS 函数怎么办?
    • @ArVan 你也可以在$add 运算符中使用数字:aplus1: {$add: ['$a', 1]}
    • 我可以在另一个计算域中使用 sum 域吗?像这样:x: {$add: ['$sum', 1]
    • @ArVan 不在同一个 $project 中,但您可以在同一管道中的后续一个中。
    • 谢谢@JohnnyHK。还有一些复杂的功能呢?假设我需要从预定义位置获取每条记录的距离? (该集合有一个位置字段)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2021-04-27
    • 1970-01-01
    • 2021-09-03
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多