$ project new field at least two fields in mongodb
As part of the aggregation pipeline, I would like to design a new field in the document that is at least two existing fields.
Below docs:
{
_id: "big1",
size: "big",
distances: { big: 0, medium: 0.5, small: 1 }
}
{
_id: "med1",
size: "medium",
distances: { big: 0.5, medium: 0, small: 0.5 }
}
{
_id: "small1",
size: "small",
distances: { big: 1, medium: 0.5, small: 0 }
}
The "spacing" subdocument shows how far the document size is from other possible sizes.
I'm looking to accumulate sorting for documents that show how close it is to a set of parameters. If I was only looking for "large" documents, I could do this:
aggregate([
{$project: {"score": "$distances.big"}}
{$sort: {"score": 1}}
]);
But suppose I want to sort the same for "large" or "medium" documents. I want something like:
aggregate([
{$project: {"score": {$min: ["$distances.big", "$distances.medium"]}}},
{$sort: {"score": 1}}
])
But that doesn't work, as $ min only works on neighboring documents in the $ group request.
Is there a way to project a value that is the minimum of the two existing fields as a sort parameter?
source to share
You can use the operator $cond
to perform a comparison that finds the minimum value using the operator $lt
:
db.test.aggregate([
{$project: {score: {$cond: [
{$lt: ['$distances.big', '$distances.medium']}, // boolean expression
'$distances.big', // true case
'$distances.medium' // false case
]}}},
{$sort: {score: 1}}
])
Result:
[
{
"_id" : "big1",
"score" : 0
},
{
"_id" : "med1",
"score" : 0
},
{
"_id" : "small1",
"score" : 0.5
}
]
source to share