1

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?

1 Answer 1

3

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] } 
                    ] 
                }  
            ]
        }
    } }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.