Check If field exists in an sub-document of an Array

后端 未结 4 1186
隐瞒了意图╮
隐瞒了意图╮ 2021-02-12 16:04

I have a schema that is similar to this.

{id: Number,
  line_items: [{ 
    id: String,
    quantity: Number,
    revi         


        
4条回答
  •  无人及你
    2021-02-12 16:28

    If you just want to get the whole document then as mentioned by @Blakes Seven. You can query using $elemMatch.
    But if you want to filter array element and get only those array elements which do not have a certain field then you can use $filter along with $type in aggregation pipeline.

    [
        { $match: { "line_items": { "$elemMatch": { "review_request_sent": { "$exists": false } } } } },
        { $project: {
            "line_items": { "$filter": { 
                "input": "$line_items", 
                "as": "item", 
                "cond": { "$eq": [ { "$type": "$$item.review_request_sent" }, "missing" ] }
            } }
        } }
    ]
    

    Note: $type returns "missing" when used with undefined fields.

提交回复
热议问题