mongodb查询之从多种分类中获取各分类最新一条记录

MongoDB获取每个分类最新一条完整记录(会话列表、每个班级成绩最高的一名学生....) 最近在做一个消息中心功能,其中有个私信功能用了MongoDB做分表存储,要解决的问题是“获取与每个人聊天的最后一条消息”,也就是像聊天软件的会话列表一样 阅读详情

文章标题有点长,吼吼。

解释下查询场景: 

现在数据表里有多条记录信息,如果对某个字段分组后,会得到不同的分组,但是不需要求各分组的count,只是想获取每个分组最新的一条全部信息记录。

例子:

有个vehicle_position表,代表车辆的位置信息,里面存放的记录如下:

{"vid" : "vid1", "position" : {  "time" : NumberLong(1489458354), "latitude" : 0, "satellitesGa" : 0, "hdop" : 0, "speed" : 20,  "longitude" : 0 } }
 "vid" : "vid1", "position" : { "time" : NumberLong(1489458355), "latitude" : 0, "satellitesGa" : 0, "hdop" : 0, "speed" : 20,  "longitude" : 0 } }
{ "vid" : "vid2", "position" : {  "time" : NumberLong(1489458354),"latitude" : 0, "satellitesGa" : 0, "hdop" : 0, "speed" : 20,  "longitude" : 0 } }
{ "vid" : "vid2", "position" : {  "time" : NumberLong(1489458355),"latitude" : 0, "satellitesGa" : 0, "hdop" : 0, "speed" : 20,  "longitude" : 0 } }
现在需求是给你一堆vid,让你查出车辆最近的位置信息,即position中的经纬度,我们不可能是一辆车一辆车的循环查。

我们可以这样写查询语句:

db.vehicle_position.aggregate([{$match: {vin: {$in: ["vid1", "vid2"]}}}, {$group: {_id: "$vin", "time": {$first: "$position.time"}, "lng": {$first: "$position.longitude"}}}, {$sort:{"position.time":-1}}])

查询结果如下:

{_id: "vid1", time: 1489458355, lng: 0, lat: 0}
{_id: "vid2", time: 1489458355, lng: 0, lat: 0}

主要就是用到了$group,$first操作符,注意需要排序。

nodejs代码块:

dataService.queryRealTimePosition = function(d, callback) {
    var db = mongojs(mongoUri);
    var vins = d.vins.split(";");
    var condition = {vin: {$in: vins}};
    db.collection(‘vehicle_position’).aggregate([
                 {$match: condition}, 
                 {$sort: {"position.time": -1}},
                 {$group: {_id: "$vin", "time": {$first: "$position.time"}, "lng": {$first: "$position.longitude"}, "lat": {$first: "$position.latitude"}}}], function(err, docs) { //注意,这里的sort操作要放在group前面进行
        if(err) {
            callback(err);
        } else {
            callback(null, docs);
        }
	db.close();
    });
};

如果想获得最早的一条记录,将$first换成$last即可。或者不用替换,将sort排序换成增序。

〖Python 数据库开发实战 - MongoDB篇⑭〗- MongoDB集合的删除记录操作 该章节我们来学习 MongoDB 增、删、改、查的最后一个知识点 - 删除记录 阅读详情

相关推荐

mongoTemplate实现统计和分组

附件为mongoDB之Java通过group函数来实现统计和分组的文档描述

MongoTemplate高级查询,过滤—>排序—>分组—>去重(按照时间倒序取最新一条数据)

在使用MongoDB时遇到的复杂查询,需要对表数据进行分组,然后取出最新一条数据 先看代码: //object是泛型,是定义的数据库映射类 private List<Object> getArchiveDataList(Request request) { TypedAggregation<Object> tagg = TypedAggregation.newAggregation(Object.class, Arrays.asList

zzztimes的博客 5039

(实测可用)STM32L431RCT6开发板-实验1 跑马灯实验

一、开发板平台简介: 1、开发板资源简介 (1)开发板主芯片型号:STM32L431RCT6 (2)开发板主芯片封装:LQFP-64_10x10x05P (3)开发板主芯片内核:ARM® Cortex®-M4 (4)开发板主芯片主频:80MHz (5)开发板主芯片Flash大小:256KB (6)开发板主芯片RAM大小:64KB

zhej2014的博客 3166

mongodb 分组获取最新一条的数据

mongodb 分组并且获取每组最新或最早一条的数据

weixin_41574517的博客 2375

Western blot (WB) 灰度分析进阶指南:ImageJ 高效定量技巧与实战优化

本文详细介绍了使用ImageJ进行Western blot灰度分析的进阶技巧,包括批量处理、背景校正和疑难条带处理等实战优化方法。通过自动化宏脚本和动态背景校正,显著提升分析效率和准确性,特别适合科研人员处理复杂WB数据。

weixin_42557830的博客 899

当Kmer遇到多倍体:复杂基因组Survey分析中的避坑指南

本文针对小麦、棉花等多倍体及高杂合复杂基因组的Survey分析,深入解析了Kmer分布图解读中的常见陷阱。文章重点探讨了如何超越理想二倍体模型,利用Smudgeplot等工具准确判断基因组倍性,并提供了从参数优化、污染判断到结果验证的全流程实战指南,帮助研究者规避错误,获得更准确的基因组大小、杂合度等关键信息。

yhn45678901的博客 1008

MongoDB如何分组后获取每组的最新记录

在统计应用项目中,经常遇到分组后,想了解每组中的日期最新记录的状态。 如有集合 project, 想了解executionProject每组日期最新的 suiteStatus,数据如下: { "_id" : ObjectId("55d4410544c96d6f6578f893"), "executionProject" : "Project1", "suiteList" : [ { "suiteStatus" : "PASS", } ], "runEndTime" : ISODate("2015-.

Raqsoft 1186

华为od统一考试B卷【宜居星球改造计划】Java&Go 实现

XXX年,人类通过对火星的大气进行宜居改造分析,使得火星已在理论上具备人类宜居的条件,由于技术原因,无法一次性将火星大气全部改造,只能通过局部处理形式,假设将火星待改造的区域为row * column的网格每个网格有3个值,宜居区、可改造区、死亡区,使用YES、NO、NA代替,YES表示该网格已经完成大气改造,NO表示该网格未进行改造,后期可进行改造,NA表示死亡区,不作为判断是否改造完成的宜居,无法穿过 初始化下,该区域可能存在多个宜居区,并且每个宜居区能同时在每个太阳日单位向上下左右四个方向的相邻格子进

MISAYAONE的博客 1万+

MongoDB获取最新一条插入的数据

如果在MongoDB存储的数据是有序的插入的,且以MongoDB自动生成的_id为集合文档的主键,那么查询集合最新一条插入的数据可以用一下方式: db.collection.find({}).sort({_id:-1}).limit(1) 默认情况下,_id 字段的类型为 ObjectID,是 MongoDB 的 BSON 类型之一. ObjectID 长度为 12 字节,由几个 2-4 字节的链组成。每个链代表并指定文档身份的具体内容。以下的值构成了完整的 12 字节组合: 一个 4 字节的值,表示

MTonj的博客 7392

【A_Star三维路径规划】基于matlab A_Star算法结合B样条平滑三维地形路径规划(含雷达威胁)【含Matlab源码 3527期】

A_Star算法结合B样条平滑三维地形路径规划(含雷达威胁) 完整代码,包运行;可提供运行操作视频!适合小白!

订阅付费专栏Matlab(奶茶价版),可赠送奶茶价版付费专栏指定代码1份; 741

YOLO系列算法改进 | 自研篇 | C3k2融合SEFN空间增强前馈网络模块 | 去模糊和提升图像细节特征,精度涨点!| WACV 2025

YOLO系列算法改进 | 自研篇 | C3k2融合SEFN空间增强前馈网络模块 | 去模糊和提升图像细节特征,精度涨点!| WACV 2025 (以YOLO26最新目标检测模型为基础,C3k2融合SEFN空间增强前馈网络模块改进Backbone)

2502_91881744的博客 237

2019-11-02mongodb查询当前记录的上一条和下一条

思路:根据当前记录的id查询前后记录。 ##mongodb实现方法: mongo可以通过时间或者通过id来判断上一条记录或者下一条记录: #通过记录的_id 上一条记录 db.数据库名称.find({ '_id': { '$lt': ids } }).sort({_id: -1}).limit(1) 下一条记录 db.数据库名称.find({ '_id': { '$gt': ids } })....

weixin_44563906的博客 1538

YOLOv11涨点改进| CVPR 2026 | 全网独家首发、特征融合改进篇| 引入SRFusion 空间细化多级融合,含多种创新融合改进,涨点可直接发论文,适合裂缝图像检测,小目标检测任务高效涨点

🔥本文提出SRFusion空间细化多级融合模块,用于改进YOLOv11网络模型。该模块通过高分辨率特征引导低分辨率语义特征的融合,利用空间注意力机制对上采样后的特征进行加权细化,增强多尺度特征间的空间细节交互。SRFusion模块能够提升模型对目标区域的表达能力,有效改善小目标、密集目标及复杂背景场景下的检测效果,同时保持YOLOv11的高效性与实时检测性能。文章详细介绍了模块结构、实现原理、核心代码及在YOLOv11中的三种配置方法,为模型优化提供了创新解决方案。

Ai缝合怪、助力小伙伴高效发论文 148

MongoDB 查询collection最新一条数据

数据库相关视频讲解:用python编程Excel有没有用处?MongoDB 查询collection最新一条数据 在MongoDB中,我们经常需要查询集合(collection)中的数据。有时候,我们只需要获取最新一条数据,这时就可以使用特定的查询语句来实现。本文将介绍如何在MongoDB中查询集合中的最新一条数据,并给...

weixin_34515452的博客 638

【人工智能】AI 智能体驾驭工程(Harness Engineering)全解析

OpenAI将Harness定义为让Agent能完成有用工作的系统工程,Harness Engineering则是持续设计、实现、迭代这套系统的方法论;Anthropic将其概括为「让模型真正成为可靠Agent的基础设施」;Martin Fowler/Thoughtworks则将其定义为「控制Agent各层循环的规格、质量检查与工作流指导体系」。强大的AI模型是一匹爆发力极强的烈马;Prompt Engineering是「对马喊话的技巧」,Context Engineering是「给马看的地图」;

奶爸的编程之路,也就一周冷个三天 5243

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Spring Data MongoRepository 获取最新一条记录

Mongodb 某张表结构示例如下: { "instanceSpec": "ecs.c6e.xlarge", "productName": "云服务器 ECS", "instanceID": "i-j6cioly7ub9e0hqh0od5", "deductedByCashCoupons": 0, "listPriceUnit": "", "billingDate": "2021-06-08", "listPrice": "", "paymentAmount": 16.18,

Defonds 的专栏 1625

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

mongo 查询 最新一条数据

public function selectNum(){ $m = new MongoDB\Driver\Manager('mongodb://0.0.0.0:27017'); $filter = array(); $options = array( 'sort' => ['_id' => -1], ...

maosaiwei的博客 6933

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

方法:查询MongoDB数据库中最新一条数据(JAVA)

使用JAVA语言查询MongoDB中某个数据库某个集合的最新一条数据: MongoCollection<Document> cpu = MongoClient.getDatabase("sysmgr").getCollection("cpu"); //获取所需集合 Document dbo = cpu.find().sort(descending("time")).first()...

weixin_30493401的博客 5334

mongodb 随机获取一条记录的方法

本文介绍php7.0以上使用mongdb的基本方法,并提供mongodb随机获取一条记录的测试实例。

傲雪星枫 2万+

pymongo篇---查询数据表中最新一条记录和多条件查询

pymongo篇---查询数据表中最新一条记录和多条件查询

心惠天意 2138

如何获取mongodb中的最后N条记录?

我找不到任何记录在案的文件。 默认情况下,find()操作将从头开始获取记录。 如何获取mongodb中的最后N条记录? 编辑:我也希望返回的结果从最近到最近排序,而不是相反。

asdfgh0077的博客 6473

php mongodb获取总数,mongodb 随机获取一条记录的方法

原理:1.先查询表中的记录总数2.随机获取偏移量为0~总记录数-13.查询时skip偏移量,再获取1条记录因本人测试环境PHP已升级到7.0以上,mongodb扩展使用支持php7.0以上的扩展,很多方法与php5.6不同。因此代码必须在php7.0以上运行。如果是php5.6环境,需要修改代码才能运行。代码如下:function.php// 连接mongodbfunction conn($hos...

weixin_35980160的博客 452

MongoDB如何查询耗时记录的方法详解

查询操作是我们日常操作数据库经常会遇到的一个功能,下面这篇文章主要给大家介绍了关于MongoDB如何查询耗时记录的相关资料 准备 在此之前,我们先在我们的数据库中插入10万条数据。数据的格式是这样的: { "name":"your name", "age":22, "gender":"male", "grade":2 } explain explain方法是用来查看db.collecion.find()的一些查询信息的。例如: db.collectionName.find().exp

Bertram的博客 3426
上一篇: cassandra安装
下一篇: ubuntu17.04出现有线网但是连接不上的问题
monkey_four
博客等级 码龄16年 11粉丝 65原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值