Use mongoose to find a key inside array of object

I have table of item list (like image). Now I wanna find a object that have name contain searchString.
I tried query like db.getCollection('vehicles').find({'result': {'name': 'A-WING FIGHTER'}}) but it look wrong.
How can I get true data in this case?

enter image description here

Upvotes: 0

Views: 922

Answers (3)

Vaibhav Gattyani
Vaibhav Gattyani

Reputation: 190

To search the array of array in MongoDB, you can use $elemMatch operator.

Try this query (This query is according to the image you shared)

db.getCollection('items').find({'results': {'$elemMatch: {'$elemMatch: {'name': 'A-WING FIGHTER'}}}})

Hope this will be helpfull.

Upvotes: 0

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

See if the following command works -

db.getCollection('vehicles').find({'results': {'name': 'A-WING FIGHTER'}})

You named result instead of results. Try if it works now...

You can also try using the following code snippet -

db.getCollection('vehicles').find({ results.name: 'A-WING FIGHTER' });

Upvotes: 0

Mohammed Yousry
Mohammed Yousry

Reputation: 2184

by this

db.getCollection('vehicles').find({ 'result': { 'name': 'A-WING FIGHTER' } })

you are searching for an exact match, so result must be an object with property name only

you should use the dot notation instead

db.getCollection('vehicles').find({ 'results.name': 'A-WING FIGHTER' })

hope it helps

Upvotes: 1

Related Questions