1

Below is the collection in MongoDB by the name- "auto_sales" and I want to select all the values of "sales" from data which is an array of object.

Collection-
{
"name" : "auto_sales", 
"data" : [ 
{ "sales" : 10, 
  "temp" : 50 }, 

{ "sales" : 9, 
"temp" : 51 }, 

{"sales" : 8, 
"temp" : 55 }, 

{"sales" : 57, 
"temp" : 7 }, 

{"sales" : 58, 
"temp" : 8 } 
] }

Is there any query to get all the values of "sales" from "data".

1 Answer 1

1

Do you mean this one:

db.collection.find(
   {},
   { "data.sales": 1 }
)

gives

{ 
    "_id" : ObjectId("5e55400d22139e9b31aa786e"), 
    "data" : [
        {
            "sales" : 10.0
        }, 
        {
            "sales" : 9.0
        }, 
        {
            "sales" : 8.0
        }, 
        {
            "sales" : 57.0
        }, 
        {
            "sales" : 58.0
        }
    ]
}

Or rather this one:

db.collection.aggregate([
   {
      $project: {
         sales: {
            $reduce: {
               input: "$data",
               initialValue: [],
               in: { $concatArrays: ["$$value", ["$$this.sales"]] }
            }
         }
      }
   }
])

or

db.collection.aggregate([
  {
    $project: {
      sales: {
        $map: {
          input: "$data",
          in: "$$this.sales"
        }
      }
    }
  }
])

gives

{ 
    "_id" : ObjectId("5e55400d22139e9b31aa786e"), 
    "sales" : [
        10.0, 
        9.0, 
        8.0, 
        57.0, 
        58.0
    ]
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good job! You can try the second query in this link: mongoplayground.net/p/BlCF0jN6vuV
If you don't mind, can you post a map-reduce version of this answer?
@bravemaster actually I never used map-reduce yet - so it would be a challenge for me.

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.