如何使用猫鼬查询集合数组中的数据 [英] how to query data inside an array of the collection using mongoose

查看:57
本文介绍了如何使用猫鼬查询集合数组中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的猫鼬模式:

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],
})

我的数据库中有大量日志,如何排序限制并跳过日志数组数据? 目前我只接受数组的最后10个元素,但我想选择应用条件.使用$ elemMatch不能解决我的问题,它可以从整个集合中显示出来,但是我需要单个文档. 希望从日期范围中查找日志. 任何建议都将受到高度赞赏.

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.

推荐答案

使用聚合框架.$ unwind您的日志数组并应用您想要的任何条件$ sort $ match,skip.或者您可以在$ project阶段检查$ filter,请发布您的预期输出,我会尽力的

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"}
}])

或者如果使用mongodb 3.2,则可以使用$ filter

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 ] }
      ] }
  }
}

这篇关于如何使用猫鼬查询集合数组中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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