MongoDB聚合查询:时间范围过滤,条件匹配,排序,分页

本示例展示如何使用MongoDB的聚合框架,实现时间范围过滤,条件匹配,排序和分页的功能。

查询条件

  • 时间范围: >= start< end
  • 服务类型: service_type = 'DISTRIBUTOR_KOREA_SEA'
  • 运单号: sinoex_no 包含 'SE'
  • 处理时间: days = 3

代码示例

MongoDB Shell 代码

// 查询条件
var start = new Date('2023-06-1T00:00:00.000+08:00')
var end = new Date('2023-06-8T00:00:00.000+08:00')
var service_type = 'DISTRIBUTOR_KOREA_SEA'

var front = '$trace_inbound.trace_time'
var back = '$trace_delivery_success.trace_time'
var day = 3

// 分组计算             
db.ceos_order.aggregate([
    {
        $addFields: {
            days: {
                $ceil: {
                    $divide: [
                        {
                            $subtract: [back, front]
                        },
                        1000 * 60 * 60 * 24 // 将毫秒转换为天数
                    ]
                }
            }
        }
    },
    {
        // where
        $match: {
            'trace_inbound.trace_time': {
                $gte: start,
                $lte: end
            },
            'service_type': service_type
        }
    },
    {
        // where
        $match: {
            'sinoex_no': {
                '$regex': 'SE'
            },
            'days': day
        }
    },{
         // 排序
         $sort: {
             _id: 1
         }
     },
    {$skip: 1},
    {$limit:10},
    {
        // as 
        $project: {
            _id: 0,
           'eawbsyscode': '$eawb_syscode',
           'eawbprintcode': '$sinoex_no',
           'eawbreference': '$tracking_no',
           'fcinbound': '$trace_inbound.trace_time',
           'fcoutbound': '$trace_outbound.trace_time',
           'ass': '$trace_ass.trace_time',
           'adc': '$trace_ata.trace_time',
           'roe': '$trace_a_scan.trace_time',
           'delivery': '$trace_delivery_success.trace_time',
           'eawbservicetype': '$service_type',
//            'route': '中外运-韩国海运',
           'eawbsocode': '$so_code',
//            'customername': '深圳市达旦外贸科技有限公司',
//            'destinyname': '韩国',
           'eawbpostcode': '$dest_post_code'
        }
    }
], {
    allowDiskUse: true
})

Java API 代码

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        // Set start and end dates
        Date start = new Date('2023-06-01T00:00:00.000+08:00');
        Date end = new Date('2023-06-08T00:00:00.000+08:00');

        // Set service type
        String serviceType = 'DISTRIBUTOR_KOREA_SEA';

        // Set day
        int day = 3;

        // Connect to MongoDB
        MongoClient mongoClient = MongoClients.create('mongodb://localhost:27017');
        MongoDatabase database = mongoClient.getDatabase('your_database_name');
        MongoCollection<Document> collection = database.getCollection('ceos_order');

        // Create the pipeline stages
        List<Bson> pipeline = Arrays.asList(
                Aggregates.addFields(
                        new Field('days',
                                new Document('$ceil',
                                        new Document('$divide',
                                                Arrays.asList(
                                                        new Document('$subtract', Arrays.asList('$trace_delivery_success.trace_time', '$trace_inbound.trace_time')),
                                                        1000 * 60 * 60 * 24 // Convert milliseconds to days
                                                )
                                        )
                                )
                        )
                ),
                Aggregates.match(
                        Filters.and(
                                Filters.gte('trace_inbound.trace_time', start),
                                Filters.lt('trace_inbound.trace_time', end),
                                Filters.eq('service_type', serviceType)
                        )
                ),
                Aggregates.match(
                        Filters.and(
                                Filters.regex('sinoex_no', 'SE'),
                                Filters.eq('days', day)
                        )
                ),
                Aggregates.sort(new Document('_id', 1)),
                Aggregates.skip(1),
                Aggregates.limit(10),
                Aggregates.project(
                        Projections.fields(
                                Projections.excludeId(),
                                Projections.computed('eawbsyscode', '$eawb_syscode'),
                                Projections.computed('eawbprintcode', '$sinoex_no'),
                                Projections.computed('eawbreference', '$tracking_no'),
                                Projections.computed('fcinbound', '$trace_inbound.trace_time'),
                                Projections.computed('fcoutbound', '$trace_outbound.trace_time'),
                                Projections.computed('ass', '$trace_ass.trace_time'),
                                Projections.computed('adc', '$trace_ata.trace_time'),
                                Projections.computed('roe', '$trace_a_scan.trace_time'),
                                Projections.computed('delivery', '$trace_delivery_success.trace_time'),
                                Projections.computed('eawbservicetype', '$service_type'),
                                Projections.computed('eawbsocode', '$so_code'),
                                Projections.computed('eawbpostcode', '$dest_post_code')
                        )
                )
        );

        // Execute the aggregate query
        MongoCursor<Document> cursor = collection.aggregate(pipeline).iterator();

        // Process the results
        while (cursor.hasNext()) {
            Document document = cursor.next();
            // Extract the desired fields from the document
            String eawbsyscode = document.getString('eawbsyscode');
            String eawbprintcode = document.getString('eawbprintcode');
            String eawbreference = document.getString('eawbreference');
            Date fcinbound = document.getDate('fcinbound');
            Date fcoutbound = document.getDate('fcoutbound');
            Date ass = document.getDate('ass');
            Date adc = document.getDate('adc');
            Date roe = document.getDate('roe');
            Date delivery = document.getDate('delivery');
            String eawbservicetype = document.getString('eawbservicetype');
            String eawbsocode = document.getString('eawbsocode');
            String eawbpostcode = document.getString('eawbpostcode');

            // Process the extracted fields as needed
            System.out.println('eawbsyscode: ' + eawbsyscode);
            System.out.println('eawbprintcode: ' + eawbprintcode);
            System.out.println('eawbreference: ' + eawbreference);
            System.out.println('fcinbound: ' + fcinbound);
            System.out.println('fcoutbound: ' + fcoutbound);
            System.out.println('ass: ' + ass);
            System.out.println('adc: ' + adc);
            System.out.println('roe: ' + roe);
            System.out.println('delivery: ' + delivery);
            System.out.println('eawbservicetype: ' + eawbservicetype);
            System.out.println('eawbsocode: ' + eawbsocode);
            System.out.println('eawbpostcode: ' + eawbpostcode);
            System.out.println('------------------------------------');
        }

        // Close the cursor and the MongoDB connection
        cursor.close();
        mongoClient.close();
    }
}

解释

  1. 时间范围过滤
    • 使用 $gte$lte 操作符过滤 trace_inbound.trace_time 字段,确保时间在 startend 之间。
  2. 服务类型过滤
    • 使用 $eq 操作符匹配 service_type 字段的值为 'DISTRIBUTOR_KOREA_SEA'
  3. 运单号过滤
    • 使用 $regex 操作符匹配 sinoex_no 字段的值包含 'SE'
  4. 处理时间过滤
    • 使用 $eq 操作符匹配 days 字段的值为 3
  5. 排序
    • 使用 $sort 操作符对 _id 字段进行升序排序。
  6. 分页
    • 使用 $skip 跳过前一条记录。
    • 使用 $limit 限制结果集大小为 10 条记录。
  7. 数据投影
    • 使用 $project 操作符选择需要返回的字段,并使用别名重命名字段。

总结

该示例展示了如何使用MongoDB的聚合框架实现时间范围过滤,条件匹配,排序和分页的功能。这些功能可以帮助你高效地查询MongoDB数据库中的数据。


原文地址: https://www.cveoy.top/t/topic/pKUc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录