0

I store documents like that:

const offer = {
  _id: UUID("b0b7bb8b-374b-4957-9902-536939f510e0"),
  name: "test name",
  products: [
    { id: "1", name: "Product name 1" }, 
    { id: "2", name: "Product name 2" }] }
  ]
};

I need query to get only id of offer and id of product for given product id:

{  _id: UUID("b0b7bb8b-374b-4957-9902-536939f510e0"), id: "1" }

To achieve that I try with query:

db.offers.find({ "products.id": "1" }, { _id: 1, "products.id": 1 })

But result was:

{ 
    _id: UUID("b0b7bb8b-374b-4957-9902-536939f510e0"),
    products: [
        { id: "1", name: "Product name 1" }, 
        { id: "2", name: "Product name 2" }
    ] 
}

How could I do that?

user
  • 4,410
  • 16
  • 57
  • 83

1 Answers1

3

Please check below query help you:

db.getCollection('offer').find({ "products.id": "1" },{"products.$":1})

Also Please correct your JSON at { id: "2", name: "Product name 2" }] }

IftekharDani
  • 3,619
  • 1
  • 16
  • 21