1

I have a collection, and inside this collection I have an array of objects called Degrees.

This array contains objects with keys {Uni:'',Level:'',Degree:''}, I want to be able to add to a parameter object the ability to find any document with a degree where level = 'BS', for example, regardless of what the other fields in the object contain.

I have tried so far:

{
  $elemMatch: {
    $eq: {
      Uni: {
        $exists: true,
        
      },
      Level: "BS",
      Degree: {
        $exists: true
      }
    }
  }
}

But it has not worked, any suggestions?

3 Answers 3

4

You can query the fields of the documents in the embedded array directly.

If your documents look something like

{
 _id:ObjectId("..."),
 Name: "",
 degrees: [
           {Uni:"",
            Level:"BS",
            Degree:""}
          ]
 }

You could return all documents that contain at least one 'BS' level degree with

db.collection.find({"degrees.Level":"BS"})
Sign up to request clarification or add additional context in comments.

Comments

3

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

I guess this should work for you :

db.collection.find({Degrees: {$elemMatch: {level:'BS'}}})

Don't forget to replace collection with ur model name. :)

Do checkout $elemMatch documetation here : mongoDb $elemMatch

Comments

1

If I'm understanding you correctly, and assuming your collection is called degrees, it should be as simple as:

// From the mongo shell:
db.degrees.find({ Level: 'BS' });

// From javascript (assuming node's native driver):
db.collection('degrees').find({ Level: 'BS' });

If you're interested in only the first result then you can use the following:

// From the mongo shell:
db.degrees.findOne({ Level: 'BS' });

// From javascript:
db.collection('degrees').findOne({ Level: 'BS' });

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.