title: MongoDB. Sort and Filter data
body: <p>I have two collections in database - "products" and "category".</p>
  
  <p>Each product have relation to categories, may inherit products of children categories for example:</p>
  
  <p>Collection "category" (category tree):</p>
  
  <pre><code>{
      "id": "1",
      "name": "Category 1", 
      "parent": None,
      "inherit": true, ...
  }
  
  {
      "id": "2",
      "name": "Subcategory 1", 
      "parent": "1", ...
  }, ...
  </code></pre>
  
  <p>Collection "product":</p>
  
  <pre><code>{
      "id": "3",
      "name": "Product",
      "categories": ["2"],
      "price": 1000, ...
  }, ...
  </code></pre>
  
  <p>I create a pages with filters of product by categories, prices and other properties and I realised sort of results by fields "name", "price" like that:</p>
  
  <pre><code>products.find({"categories": {"$in": ["1", "2"]}, "price": {"$gte": 1000, "$lte": 5000}}).sort({"price": -1})
  </code></pre>
  
  <p>Now, I need to manually set product's order for each category. 
  How can I do that? </p>
  
  <p>Also, category may have more than 10000 products, but after filtering I want, that order of filtered products will stay as it's been before filtering, only without products that doesn't match filter conditions.</p>
  
  <hr>
  
  <p>I think I need something like this, but i'm not sure:
      products.find({"categories": {"$in": ["1", "2"]}, "price": {"$gte": 1000, "$lte": 5000}}).sort({"category_order.1": 1})</p>
  
  <p>and in each product add dict {"category_order": {"1": 1, "2": 1}}, where keys is category_id, and value is order in category.</p>
  
  <p>Any ideas?</p>