3

I do some filter with mongodb but it return all of the data in my array. But i only want to get the specific element from that array. I cant find it in the document.

db.sales.aggregate([
       {
          $project: {
             items: {
                $filter: {
                   input: "$items",
                   as: "item",
                   cond: { $gte: [ "$$item.price", 100 ] }
                }
             }
          }
       }
    ])

Run above command I will this is result

{
   "_id" : 0,
   "items" : [
      { "item_id" : 2, "quantity" : 1, "price" : 240 }
   ]
}

Question is I only want to get the price

  {
       "_id" : 0,
       "items" : [
          { "price" : 240 }
       ]
    }

or even

{
    "price" : 240 
}

How to do it?

1

2 Answers 2

2

You actually need $map to "alter" the array elements returned, as $filter only "selects" the array elements that "match". Try to run the below code.

ds.sales.aggregate([
    {
        $project: {
            items: {
                $map: {
                    input: {
                        $filter: {
                            input: "$items",
                            as: "item",
                            cond: { $gte: [ "$$item.price", 100 ] }
                         }
                    },
                    "as": "a",
                    "in": {
                        "price": "$$a.price"
                      }
                }
            }
        }
    }], function (err, list) {
    ...
Sign up to request clarification or add additional context in comments.

Comments

1

I don't know your whole data looks like, if your data looks like this

{
    "_id" : 0,
    "items" : [
        {
            "item_id" : 1,
            "quantity" : 5,
            "price" : 80
        },
        {
            "item_id" : 2,
            "quantity" : 1,
            "price" : 240
        },
        {
            "item_id" : 3,
            "quantity" : 4,
            "price" : 320
        }
    ]
}

Just try this

> db.sales.aggregate([
    {'$unwind': '$items'},
    {'$project': {'price': '$items.price'}},
    {'$match' : {'price': {'$gte': 100 }}}
])
{ "_id" : 0, "price" : 240 }
{ "_id" : 0, "price" : 320 }

$unwind

{'items': [{'item_id': 1}, {'item_id': 2}]} 

after $unwind

{'items': {'item_id': 1}}
{'items': {'item_id': 2}} 

$project

This can choose which field you want ( or just remove which field you don't want) and rename a field to what you want.

{'items': {'item_id': 1}}

after $project

{'renamefor__item_id': 1}

$match

Just see the previous link for more detail. My English is not very good:(

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.