mongodb - Sort by subdocuments fields in mongo -
given following collection:
[ { name: user1 metadata: [ {k:"score", v: 5}, {k:"other", v: 10} ] }, { name: user2 metadata: [ {k:"score", v: 1}, {k:"other", v: 1} ] }, { name: user3 metadata: [ {k:"score", v: 2}, {k:"other", v: 0} ] } ]
how can sort these items "score"? can sort metadata.v field, not sure how consider "v" values subdocuments match "k":"score"
the expected output be:
[ { name: user2 metadata: [ {k:"score", v: 1}, {k:"other", v: 1} ] }, { name: user3 metadata: [ {k:"score", v: 2}, {k:"other", v: 0} ] }, { name: user1 metadata: [ {k:"score", v: 5}, {k:"other", v: 10} ] } ]
an alternative solution this, whereby final projection stage optional if can live additional scoredata
property.
db.yourcollection.aggregate([ { $project: { name: 1, metadata: 1, scoredata: { $filter: { input: '$metadata', as: 'metadoc', cond: { $eq: [ '$$metadoc.k', 'score' ] } } } } }, { $sort: { scoredata: 1 } }, { $project: { name: 1, metadata: 1 } } ])
output looks
/* 1 */ { "_id" : objectid("5796387b3360e0a2e9dd9fc3"), "name" : "user2", "metadata" : [ { "k" : "score", "v" : 1 }, { "k" : "other", "v" : 1 } ] } /* 2 */ { "_id" : objectid("5796387b3360e0a2e9dd9fc4"), "name" : "user3", "metadata" : [ { "k" : "score", "v" : 2 }, { "k" : "other", "v" : 0 } ] } /* 3 */ { "_id" : objectid("5796387b3360e0a2e9dd9fc2"), "name" : "user1", "metadata" : [ { "k" : "score", "v" : 5 }, { "k" : "other", "v" : 10 } ] }
Comments
Post a Comment