'mongodb aggregation add field derived from another field
here is my data which I need to add in a collection
let data = {
'a':'data a',
'ab':'data a',
'b':'data b',
'c':'data c'
}
here is my collection data:
{
name:'xyz',
age:'100',
arr: ['a','ab']
}
what I want:
{
name:'xyz',
age:'100',
arr: ['a','ab'],
data:'data a' //get this from arr first element, and that is key in data object that's value here
}
can someone help me to write this query in mongoose?
Solution 1:[1]
You need an aggregate operation that makes use of the following pipeline stages and operators:
$addFields: adds a new field to the pipeline documents$objectToArray: converts an object/document to an array. This is necessary for checking the index of matching array elements$arrayElemAt: gets the element at the specified array index$indexOfArray: gets the the array index (zero-based) of the first occurrence of a specified value
Your final pipeline should be as follows:
let data = {
'a':'data a',
'ab':'data a',
'b':'data b',
'c':'data c'
};
db.collection.aggregate([
{ $addFields: {
data: { $objectToArray: data },
} },
{ $addFields: {
data: {
$arrayElemAt: [
'$data.v',
{
$indexOfArray: [
'$data.k',
{ $first: '$arr' }
]
}
]
}
} }
])
OR
db.collection.aggregate([
{ $addFields: {
data: { $objectToArray: data },
} },
{ $addFields: {
data: {
$arrayElemAt: [
'$data.v',
{
$indexOfArray: [
'$data.k',
{ $arrayElemAt: ['$arr', 0] }
]
}
]
}
} }
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chridam |
