如何在Mongoose中查询不同的值,但返回所有文档? [英] How do I query for distinct values in Mongoose but return all of the doc?

查看:262
本文介绍了如何在Mongoose中查询不同的值,但返回所有文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用猫鼬及其独特的功能...如何将查找与正则表达式和Distict相结合,并返回完整文档?

Using mongoose and it's distinct function... how can i combine a find with regex and distict, and return the full document?

使用独特的功能 https://docs. mongodb.com/manual/reference/method/db.collection.distinct/#options 仅返回唯一字段.

Using the distinct function https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#options just returns the unique fields.

这就是我和lodash拼凑的东西.

This is what i instead cobbled together with lodash..

findByTitle: ( title ) => {
    return new Promise( ( resolve, reject ) => {

        solutionModel.find( {"Title": { $regex: new RegExp( title ,'i') }}, (err, docs) => {
            if( err ) return reject( err );

            return resolve( _.uniqBy(docs, (e) => {
                return e.SolutionID;
            }) );
        });

    } );
},

使用汇总跟踪:

solutionModel.aggregate(
    [
        { "$match": {
            "Title": { $regex: new RegExp( 't' ,'i') }
        }},
        // Grouping pipeline
        { "$group": {
            "SolutionID": '$SolutionID'
        }},
        // Sorting pipeline
        { "$sort": { "Title": -1 } },
        // Optionally limit results
        // { "$limit": 5 }
    ],
    function(err,docs) {

        console.log( err );
        console.log( docs );
    }
);

结果错误:

MongoError:字段"SolutionID"必须是一个累加器对象

MongoError: The field 'SolutionID' must be an accumulator object

推荐答案

$ group的语法错误.请阅读 https://docs.mongodb.com/manual/reference/operator /aggregation/group/.

Wrong syntax for $group. Please read https://docs.mongodb.com/manual/reference/operator/aggregation/group/.

例如按SolutionID分组,将第一个匹配的文档存储在"doc"中:

E.g. grouping by SolutionID, storing the first matching document in 'doc':

{ "$group": {
    _id: "$SolutionID",
    doc: {$first: "$$ROOT"}
}

这篇关于如何在Mongoose中查询不同的值,但返回所有文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆