search

Home  >  Q&A  >  body text

mongodb array query - How to filter subdocuments when querying MongoDB?

There is a document, which contains a subdocument, roughly as follows:

{
    "_id" : ObjectId("59376b35a233be856d4a0731"),
    "plate_number" : "京A11111",
    "breakdown" : [
        {
            "file_id" : "4003732",
            "case_number" : "xxxx",
            "lev_code" : "B231",
            "crdate" : ISODate("2016-01-19T17:00:43Z")
        },
        {
            "file_id" : "4010523",
            "case_number" : "xxxx",
            "lev_code" : "B231",
            "crdate" : ISODate("2016-06-29T14:53:36Z")
        },
        {
            "file_id" : "4010980",
            "case_number" : "xxxx",
            "lev_code" : "B211",
            "crdate" : ISODate("2016-07-01T17:18:40Z")
        }
    ]
}

The current requirement is how to use PHP 7 to query the number of matches based on plate_number & lev_code

Another question is, how to match subdocuments that meet the conditions?

# mongo
find({plate_number:"京A11111", breakdown.lev_code:"B231"})
{
    "breakdown" : [
        {
            "file_id" : "4003732",
            "case_number" : "xxxx",
            "lev_code" : "B231",
            "crdate" : ISODate("2016-01-19T17:00:43Z")
        },
        {
            "file_id" : "4010523",
            "case_number" : "xxxx",
            "lev_code" : "B231",
            "crdate" : ISODate("2016-06-29T14:53:36Z")
        },
        {
            "file_id" : "4010980",
            "case_number" : "xxxx",
            "lev_code" : "B211",
            "crdate" : ISODate("2016-07-01T17:18:40Z")
        }
    ]
}
阿神阿神2772 days ago946

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-06-10 09:50:08

    It is recommended to use MongoDB’s aggreation’s $filter:

    https://docs.mongodb.com/mast...

    Love MongoDB! Have fun!

    reply
    0
  • Cancelreply