Home > Software design >  Perform and query in mongo db
Perform and query in mongo db

Time:09-15

I have a collection of forms that looks like that:

    {
     id:1,
     Pages: [{
        Fields: [{ 
            FieldName: 'field1',
            Value:'the fox'
           },
           {
            FieldName: 'field2',
            Value:'is brown'
           }]
   }, 
   {
    id:2,
    Pages: [{
     Fields: [{ 
         FieldName: 'field1',
         Value:'jumps'
        },
        {
         FieldName: 'field2',
         Value:'the fox'
        }]
   }
]

I would like to retrieve only the documents where the FielName 'field1' equals 'the fox'.

I tried something like {'Pages.Fields.FieldName':'field1', 'Pages.Fields.Value:'the fox'} which I expected to create an and query, but this actually returns both documents instead of only the first one.

Is there a way to achieve this ?

CodePudding user response:

You should use $elemMatch operator:

db.collection.find({
  "Pages.Fields": {
    "$elemMatch": {
      "FieldName": "field1",
      "Value": "the fox"
    }
  }
})

Mongodb playground ref: https://mongoplayground.net/p/gn2DAIVtEZD

  • Related