0

I have an collection like:

{
   _id: 0,
   items: [
     { item_id: 43, quantity: 2, price: 10 },
     { item_id: 2, quantity: 1, price: 240 }
   ],
   T: [
     { item_id: 2993, quantity: 3, price: 110 },
     { item_id: 90103, quantity: 4, price: 5 },
     { item_id: 398, quantity: 1, price: 300 }
    ]
}
{
   _id: 1,
   items: [
     { item_id: 23, quantity: 3, price: 110 },
     { item_id: 103, quantity: 4, price: 5 },
     { item_id: 38, quantity: 1, price: 300 }
   ],
   T: [
     { item_id: 23, quantity: 3, price: 110 },
     { item_id: 103, quantity: 4, price: 5 },
     { item_id: 38, quantity: 1, price: 300 }
     ]
}
{
    _id: 2,
    items: [
       { item_id: 4, quantity: 1, price: 23 }
    ],
   T: [
     { item_id: 203, quantity: 3, price: 110 },
     { item_id: 003, quantity: 4, price: 5 },
     { item_id: 398, quantity: 1, price: 300 }
     ]
}

I want to return a all the items in the items array with a price >= 100. That is done with the following:

   $project: {
         items: {
            $filter: {
               input: "$items",
               as: "item",
               cond: { $gte: [ "$$item.price", 100 ] }
            }
         }
      }

How can I expand this expression to $filter on the items array and the T array all elements that have a price >= 100?

1
  • Hi JohnnyHK, i want to basically filter on both the T and items array with the same condition. So I expect the output to be all the documents with the T and items array only containing elements with a price >= 100 Commented May 9, 2016 at 14:12

1 Answer 1

1

You can include both the items and T fields in the same $project, each with its own $filter:

db.test.aggregate([
    {$project: {
        items: {
            $filter: {
               input: "$items",
               as: "item",
               cond: { $gte: [ "$$item.price", 100 ] }
            }
        },
        T: {
            $filter: {
               input: "$T",
               as: "t",
               cond: { $gte: [ "$$t.price", 100 ] }
            }
        }
    }}
])
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.