使用MongoDB + Sails.js进行复杂排序

时间:2015-11-25 19:41:38

标签: node.js mongodb sails.js mongodb-query aggregation-framework

我正在使用Sails.js和MongoDB开发Web应用程序。我必须查询数据库并通过复杂的函数对结果进行排序。实际上并不复杂,但比按键排序更困难。在这种情况下,我有这个集合

用户

/// <summary>
/// Form with "skeleton" common for your application.
/// </summary>
public partial class FormWithPicture : Form {
    private Control content;
    /// <summary>
    /// The control which should be used as "main" content of this form.
    /// </summary>
    public Control Content {
        get { return this.content; }
        set {
            this.content = value;
            // the "panel1" is the container of the content
            this.panel1.Controls.Clear();
            if (null != value) {
                this.panel1.Controls.Add(value);
            }
        }
    }

    public FormWithPicture() {
        InitializeComponent();
    }
}

// somewhere else
new FormWithPicture {
    Content = new ContentControl_A()
}.Show();

我正在尝试按{ user : "Luis", key1 : 23, key2 : 29 }; { user : "Juan", key1 : 53, key2 : 22 }; { user : "Paco", key1 : 26, key2 : 42 };

获取结果顺序

我尝试过使用Mongo complex sorting?帐户的不同查询,但这对我没有帮助。

key1 - key2

我已经检查过这种方式在Robomongo控制台(MongoDB GUI客户端)中运行正常。

User.find({}).sort(function(doc1,doc2){return doc1.a . doc2.b })
 .exec(function(err,users){console.log(users)});

但是我无法使用Sails和waterline orm实现这一点。如果有必要,我会使用原生连接,但我不知道该怎么做。

请帮助我,非常感谢你!

2 个答案:

答案 0 :(得分:2)

您需要使用.aggregate()方法来提供对聚合管道的访问。管道的第一个阶段是$project阶段,您可以使用$subtract运算符返回&#34; key1&#34;的差异。和&#34; key2&#34;。

管道中的最后一步是$sort阶段,您可以使用{ 'diffkey': 1 }或降序{ 'diffkey': -1 }按升序对文档进行排序。

db.user.aggregate([
    { '$project': { 
        'user': 1, 
        'key1': 1, 
        'key2': 1, 
        'diffkeys': { '$subtract': [ '$key1', '$key2' ] }
     }}, 
    { '$sort': { 'diffkeys': 1 } }
])

哪个收益率:

{
        "_id" : ObjectId("567d112eaac525feef33a5b7"),
        "user" : "Juan",
        "key1" : 53,
        "key2" : 22,
        "diffkeys" : -31
}
{
        "_id" : ObjectId("567d112eaac525feef33a5b6"),
        "user" : "Luis",
        "key1" : 23,
        "key2" : 29,
        "diffkeys" : 6
}
{
        "_id" : ObjectId("567d112eaac525feef33a5b8"),
        "user" : "Paco",
        "key1" : 26,
        "key2" : 42,
        "diffkeys" : 16
}

您可能想要在管道中添加另外一个$project来过滤掉查询结果中的diffkey字段,但这样做会导致性能下降。一般来说,您不必担心查询结果中的一个额外字段。

答案 1 :(得分:1)

如果您的意思是按key1key2之间的差异排序,我认为可以通过简单的查找来完成,我认为您需要使用聚合。

注意:我不熟悉Sail.js,所以我会在mongoshell中编写查询并让你翻译成帆

db.user.aggregate([
{
    $project:{
        doc: "$$ROOT",
        sortOrder: { $subtract: ["$key1", "$key2"] }
    }
},
{
    $sort:{ sortOrder: 1}
}
]);

不确定您希望最终输出的确切外观,因此您可能希望在最后添加其他项目。