按elemMatch在MongoDB中排序

编程入门 行业动态 更新时间:2024-10-27 08:24:35
本文介绍了按elemMatch在MongoDB中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在MongoDB中是否有一种基于$elemMatch的排序方式?例如,我有看起来像这样的文档:

Is there a way of sorting in MongoDB based on an $elemMatch? For example, I have documents which look like this:

{ 'user': ObjectId('fsdfsdf'), ... 'array_of_things': [ { 'attribute_1': ObjectId('sdfsdfsd'), 'attribute_2': ObjectId('sdfsfsdf'), 'value': 30000 }, { 'attribute_1': ObjectId('dfdfgfdg'), 'attribute_2': ObjectId('gdfgdfgd'), 'value': 100 }, { 'attribute_1': ObjectId('mbnmbbmb'), 'attribute_2': ObjectId('mbnmbnmb'), 'value': 2000 }, ... ] }

我需要能够基于array_of_things字段内的匹配元素来查询此数据(使用$elemMatch足够简单).出现问题是因为我还需要能够按与某个属性匹配的值(升序或降序)进行排序.例如,查询可能是:

I need to be able to query this data based on a matching element inside the array_of_things field (which is simple enough with an $elemMatch). The problem arises because I also need to be able to sort by value (ascending or descending) that match a certain attribute. For example, a query might be:

{ 'user': ObjectId('fsdfsdf'), 'array_of_things': { $elemMatch: { 'attribute_1': ObjectId('dfdfgfdg'), 'value': { $gt: 1 } } } }

仅对value进行排序(例如,按预期,sort({ 'array_of_things.value': -1 })仅对任何数组元素中的所有值进行排序,而不是首先与attribute_1匹配.

Sorting solely on value (e.g. sort({ 'array_of_things.value': -1 }) predictably only sorts on all values in any array element, not matching attribute_1 first.

有没有办法做到这一点?

Is there a way to do this?

很抱歉,如果这是一个已经提出的问题,但是看完之后我似乎找不到任何解决方案.

Apologies if this is an already-asked question, but I can't seem to find any solution to it after looking.

推荐答案

当前无法使用标准查询语言来实现.您可以使用聚合框架(可能)在性能上有所损失.

This is currently not possible with the standard query language. You can achieve it with the aggregation framework at (potentially) some performance penalty.

更多推荐

按elemMatch在MongoDB中排序

本文发布于:2023-11-22 05:17:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:elemMatch   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!