MongoDB querying nested documents with filters

Viewed 45

My MongoDB document looks something like this -

{

"VENDOR_ID": "101",
"NAME": "Test",
"DELETEFLAG": "1",
"DATETIME_MODIFIED": "2021-04-22 05:31:27am",
"CONTACT": [{
    "CONTACT_ID": "111",
    "CONTACT_TYPE": "CONTACT",
    "DELETEFLAG": "1",
    "LID": "197",
    "USER_ID": "101",
    "VALUE": "222222222222"
}, {
    "CONTACT_ID": "222",
    "CONTACT_TYPE": "EMAIL",
    "DELETEFLAG": "1",
    "LID": "197",
    "USER_ID": "101",
    "VALUE": "Test@gmail.com"
}, {
    "CONTACT_ID": "333",
    "CONTACT_TYPE": "CONTACT",
    "DELETEFLAG": "2",
    "LID": "197",
    "USER_ID": "101",
    "VALUE": "444444444444"
}, {
    "CONTACT_ID": "444",
    "CONTACT_TYPE": "CONTACT",
    "DELETEFLAG": "2",
    "LID": "197",
    "USER_ID": "101",
    "VALUE": "888888888888"
}]

}

I want to fetch all the Contacts for which the **DELETEFLAG** is set to 1. My collection can have multiple vendor documents.

I'm using PHP and fetching all the VENDORS with DELETEFLAG set to 1 along with their contacts. My query looks something like this -

$filterproduct = array(
                "CONTACT.DELETEFLAG"=>'1',
                "DELETEFLAG" => '1',
                "LID"=>$LID,
          ); 
$resultproduct1 = $this->GetMany($collectionName,$filterproduct,$fetchArr);

 
1 Answers

If I understand, you maybe want this:

db.collection.aggregate([
  { $unwind: "$CONTACT" },
  {
    $match: {
      "CONTACT.DELETEFLAG": "1",                
    },
  },   
]);

Yopu break all documents in contacts with $unwind and so, get only new generated documents with CONTACT.DELETEFLAG = 1 with $match.

Related