简体   繁体   English

猫鼬,如何查询对象数组中的最大值或最小值并返回对象

[英]mongoose, how to query the maximum or minimum value in the a object-array and return the object

I have the array[object] schema: 我有array [object]模式:

var operation = new Schema({
    name:{type:String},
    number:[Number],
});

var Info = new Schema({
    serialNumber:{type:Number}
    operation:[operation],
}); 

the data example: 数据示例:

{
   serialNumber: 25,
   operation:[
     {
        name:'jack',
        number:1,
     },{
        name:'may',
        number:2,
     },{
        name:'alexander ',
        number:3,
     },
   ]
}

how to query the collection when serialNumber: 25 && operation.number is maximum and return the object, serialNumber: 25 && operation.number为最大值并返回对象时,如何查询集合,

In this case will return this 在这种情况下将返回此

{
  name:'alexander ',
  number:3,
},

I have try it aggregate() sort() 我试过了aggregate() sort()

but aggregate() can't select a condition (ex: serialNumber: 25 ) and can't return single object, find().sort() can select a condition,but unable to sort inner array objects. 但是aggregate()无法选择条件(例如: serialNumber: 25 )并且无法返回单个对象, find().sort()可以选择条件,但无法对内部数组对象进行排序。

You should probably go back a read the documentation on the aggregation pipeline since you seem to be mistaken on how it is used and what it does. 您可能应该回过头来阅读有关聚合管道的文档,因为您似乎在使用方式和用途上似乎有误。 The steps for this using the aggregation pipeline are a little long but you can do all of this pretty easily. 使用聚合管道的步骤很长,但是您可以轻松完成所有这些工作。 There are probably some shortcuts to take but here's the long version. 可能有些捷径可走,但这是长版。

db.getCollection('bar').aggregate([
    {$match: {serialNumber: <number>}}, //use match to find based on serial number
    {$unwind: '$operation'}, //unwind the operation array
    {$sort: {'operation.number': -1}}, //sort operation number desc
    {$limit: 1}, //get only first item
    {$project: {_id: 0, name: '$operation.name', number: '$operation.number'}} //project the object and attributes you want
])

You can then take the first item off the results array or look into returning a cursor from the aggregation framework. 然后,您可以从results数组中删除第一项,也可以考虑从聚合框架返回游标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM