djangomongodbmongodb-querydjongo

Crop mongo document with filter


The project stack is Django + MongoDB (djongo library).
I have order table with data structure like this

{
  name:"Help",
  price:123,
  products:[
    {
      "_id":"some id",
      "organization":{
        "id":1
      }
    },
    {
      "_id":"some id2",
      "organization":{
        "id":2
      }
    }
  ]
}

How can I get list order which has item in 'products' set where organization id field is equal 1?

When I will get this list how can I delete products set items where organization id field isn't equal 1?

So I should get something like this (Price field shouldn't be too)

{
  name:"Help",
  products:[
    {
      "_id":"some id",
      "organization":{
        "id":1
      }
    }
  ]
}

Solution

  • Query

    *you can use project also it is the same, but $set leaves all other fields you possible have unchanged

    Test code here

    aggregate(
    [{"$set":
      {"price":"$$REMOVE",
       "products":
       {"$filter":
        {"input":"$products",
         "cond":{"$eq":["$$this.organization.id", 1]}}}}}])