1

I am new to MongoDB.

This is my 'masterpatients' collection it has many documents. every documents contain 'visits' array and every visits array contains multiple objects. I want only those object which is satisfied with my input. I am expecting only below the expected output. if the facility match with my input and visit date range match with my provided input then the query should return only that object as I have given below.

_id:5ef59134a3d8d92e580510fe
    flag:0
    name:"emicon_test"
    dob:2020-06-25T00:00:00.000+00:00
    visits:[
     {
        visit:2020-06-09T10:36:10.635+00:00,
        facility:"Atria Lady Lake"
     },
    { 
       visit:2020-05-09T10:36:10.635+00:00,
       facility:"demo"
    }]
    
    _id:5ee3213040f8830e04ff74a8
    flag:0
    name:"xyz"
    dob:1995-06-25T00:00:00.000+00:00
    visits:[
     {
        visit:2020-05-01T10:36:10.635+00:00,
        facility:"pqr"
        
     },
    {
       visit:2020-05-15T10:36:10.635+00:00,
       facility:"demo"
       
    },
    {  
       visit:2020-05-09T10:36:10.635+00:00,
       facility:"efg"
    }]

My query input parameters is facility='demo' and visit date range is from '1st May 2020' to '10th May 2020'

output expected:

_id:5ef59134a3d8d92e580510fe
    flag:0
    name:"emicon_test"
    dob:2020-06-25T00:00:00.000+00:00
    visits:[
    { 
       visit:2020-05-09T10:36:10.635+00:00,
       facility:"demo"
    }]

Thanks in advance.

6
  • 1
    Have you tried $elemMatch Commented Jul 2, 2020 at 3:01
  • @Joe yes but it returns a whole array, not a specific object as I mention output. Commented Jul 2, 2020 at 3:24
  • what filters did you use in the elemMatch? Commented Jul 2, 2020 at 3:25
  • Joe I have used $gte and $lte filter Commented Jul 2, 2020 at 4:11
  • can you edit that query into the question Commented Jul 2, 2020 at 4:12

2 Answers 2

1

I got an answer.

MasterPatientModel.aggregate([
                {
                    '$unwind':"$visits"
                },
                {"$match": {"visits.visit": {"$gte": new Date(req.body.facilitySummaryFromdate), "$lte": new Date(req.body.facilitySummaryTodate)
                                            } ,  "visits.facility":  req.body.facilitySummary
                           }
                }
    ])
Sign up to request clarification or add additional context in comments.

Comments

0

You cannot filter the contents of a mongo collection property on the server.

Make visits array into a top level collection/model and you can filter by criteria on the server.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.