Reputation: 1459
I have the array[object] schema:
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,
In this case will return this
{
name:'alexander ',
number:3,
},
I have try it 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.
Upvotes: 0
Views: 1269
Reputation: 2636
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.
Upvotes: 1