Mongo查找和项目嵌套字段

时间:2018-11-06 13:34:51

标签: mongodb mongodb-query

我这样存储文档:

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" }] }
  ]
};

我需要查询以获得给定产品ID的商品ID和产品ID:

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

要实现这一点,我可以尝试使用查询:

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

但是结果是:

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

我该怎么办?

1 个答案:

答案 0 :(得分:1)

  

请检查以下查询是否对您有帮助:

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

也请在{ id: "2", name: "Product name 2" }] }上更正JSON