0

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.

1
  • Can you show an example query that you have tried and what your expected output is with some sample documents? Commented Nov 20, 2016 at 12:39

1 Answer 1

2

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 ] }
      ] }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

i want to fetch logs from $gte:"a_date", $lte:"a_date"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.