【问题标题】:How to get data from mongodb on basis of length of array inside mongo database?如何根据 mongo 数据库中数组的长度从 mongodb 获取数据?
【发布时间】:2018-06-26 01:03:07
【问题描述】:

这是我的猫鼬活动模式。

var Activity = new Schema({
    activityName: {
        type: String,
        required: true
    },
    activityPlace: {
        name: {
            type: String,
            default: 'Virtual'
        },
        location: {
            type: {
                type: String,
                default: 'Point'
            },
            coordinates: {
                type: Array,
                default: [0, 0]
            }
        },
    },
    activityCategory: {
        type: String,
        required: true
    },
    createdBy: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    usersAttending: [{
        type: Schema.ObjectId,
        ref: 'User'
    }],
});

它有一个字段“usersAttending”。 这是我调用这个 mongo 活动模型的函数。

var getActivityNearbyFeed = function (location, distance, id, page, pagesize, callback) {
    var criteria = {
        "createdBy": {
            $ne: id
        },
        "activityPlace.location.coordinates": {
            $geoWithin: {
                $centerSphere: [
                    location.coordinates,
                    distance
                ]
            }
        },
    };

    var projection = {};

    var option = {
        lean: true
    }
    var query = Models.Activity.find(criteria, projection, option);
    query.skip(page * pagesize);
    query.limit(pagesize);
    //query.sort();
    query.exec(function (err, data) {
        if (err) {
            callback(err);
        } else {
            callback(null, data);
        }
    })
};

我想根据数组 usersAttending 的长度对数据进行排序。我正在获取查询对象中的数据,有什么方法可以让我根据 usersAttending 数组的长度在该对象中获取数据。我使用了 sort 函数,但找不到正确的语法。提前致谢。

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

很遗憾,您不能直接这样做。最简单的答案是维护一个 length 变量,用于跟踪数组长度,每次在数组中完成插入时递增它并递减以删除。

另一种方法是使用.aggregate() 方法,如How to sort documents based on length of an Array field 所述。虽然对于您的查询,写起来确实很复杂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多