Reputation: 484
i have a mongoose schema like this :
var LogsSchema = new Schema({
date: Date,
longitude: String,
latitude: String,
speed: Number
});
var DeviceSchema = new Schema({
name: String,
model: String,
phone: {
type: Number,
required: true,
unique: true
},
push: Number,
logs: [LogsSchema],
})
i have huge array of logs in my database how can i sort limit and skip logs array data ?? currently i am taking only last 10 elements of array but i want to select applying condition . Using $elemMatch doesnot solve my problem it shows from whole collection but i need from individual documents. what is wish is to find logs from date range. Any suggestions are highly appreciated.
Upvotes: 0
Views: 840
Reputation: 1646
use aggregation framework.$unwind your log array and apply whatever condition you want $sort $match,skip.or you can check $filter in $project stage,please post your expected output I will try my hand
db.collection.aggregate([{"$unwind" : "$logs"},
{$match : {"$and" : [{"logs.date" :{$gte : fromDate} },
{"logs.date" :{"$lte" : toDate}}]}},
{"$group" : "_id" : "_id",
"logs" : {"$push" : "$logs"},
"names" :{"$first" : "$name"}
}])
Or you can use $filter if using mongodb 3.2
{
$filter: {
input: logs,
as: "num",
cond: { $and: [
{ $gte: [ "$$num.date", fromDate ] },
{ $lte: [ "$$num.date", toDate ] }
] }
}
}
Upvotes: 2