【问题标题】:how to ignore other fields while doing match a field in array in mongodb?如何在匹配mongodb数组中的字段时忽略其他字段?
【发布时间】:2020-07-30 17:07:42
【问题描述】:

收藏是

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

查询是

db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)

它返回

{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }

但我也想在返回 json 时忽略 { "product" : "abc", "score" : 7 }。我尝试了其他匹配 aswel 仍然与其他记录一起返回。如何处理?请帮助谢谢

【问题讨论】:

标签: arrays mongodb mongoose mongodb-query


【解决方案1】:

您需要使用位置运算符$ 投影匹配结果,否则它将始终返回与查询匹配的完整文档。 (因此为什么你会得到完整的结果)。

db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } },
   { "results.$": 1 }
)

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多