MongoDB - How to find all objects within an array?

后端 未结 2 816
夕颜
夕颜 2020-12-12 02:50

I\'m trying to find all elements within an array called programme. The result of running db.base.find({\"programme.title\":\"News\"},{\"programme

相关标签:
2条回答
  • 2020-12-12 03:24

    Projection to a match in MongoDB .find() queries can only return the "first" element matching your conditions.

    So to get "multiple" matches your best approach is using .aggregate() and $redact, with first filtering the documents with $match:

    db.base.aggregate([
        { "$match": { "programme.title":"News" } },
        { "$redact": {
            "$cond": {
                "if": { "$eq": [ { "$ifNull": [ "$title", "News" ] }, "News" } ],
                "then": "$$DESCEND",
                "else": "$$PRUNE"
            }}
        }}
    ])
    

    This "removes" ("redacts") any entries from the array that do not match the "title" you are giving.

    This is a good approach since you are not creating more documents in the pipeline using $unwind, which is another way to work with arrays.

    The catch is that you cannot have another element in your document with the same property name "title", as the $$DECEND walks into the structure and compares the field names at each level.

    0 讨论(0)
  • 2020-12-12 03:27

    You can achieve with the help of Aggregation as below :

     db.base.aggregate([
        {$unwind : "$programme"},
        {$match : { "programme.title" : "News" } },
       {$group : { "_id" : "$_id" , "programme" : { $push: "$programme" } } }
    ]);
    
    0 讨论(0)
提交回复
热议问题