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

后端 未结 4 539
后悔当初
后悔当初 2021-02-12 15:38

I have a schema that is similar to this.

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


        
4条回答
  •  执笔经年
    2021-02-12 16:42

    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.

提交回复
热议问题