Sign In Register

How can we help you today?

Start a new topic
Answered

How to find document by array

Hi, I have collection of songs with and each of them have an array of artists I'm trying to find a document by an artist in the array in mongodb but I can't figure out how to do this. 


I've tried { "artists": {"$elemMatch":{"$eq":"Imagine Dragons"}} } , { "artists": ["Imagine Dragons"] } also tried with $all and $in and none of this returns anything, anyone can help me with this?


Thanks


Best Answer

 Hey Hjupter,

Can you show an example of what you doc looks like?
The $in operator should work if you have only single fields in your doc, but if i can see an example of the doc i can help further.

So, if you doc looked something like this...

{  "artists" : [ "a", "b", "c", "s"  ]  }

You could query it like this....

collection.find({ "artists" : { $in : [ "a" ]  } });

Let me know if that works for you.
Thanks,
Sean


Answer

 Hey Hjupter,

Can you show an example of what you doc looks like?
The $in operator should work if you have only single fields in your doc, but if i can see an example of the doc i can help further.

So, if you doc looked something like this...

{  "artists" : [ "a", "b", "c", "s"  ]  }

You could query it like this....

collection.find({ "artists" : { $in : [ "a" ]  } });

Let me know if that works for you.
Thanks,
Sean

I see all I had to do is this:


{ "artists" : [{"name": "Imagine Dragons"}] }

My previous post was not posted :/


I noticed the array contained objects and not strings, here is an example document:


 

{
  "_id": {
    "$oid": "58e3f2c210f3f60557d78f87"
  },
  "title": "Demons",
  "label": "Universal Music A/S",
  "release_date": "2012-01-01",
  "listenedDate": "4/4/2017",
  "addedDate": "4/4/2017",
  "lastPlayDate": "",
  "album": {
    "name": "Continued Silence EP"
  },
  "genres": [
    {
      "name": "Alternative"
    }
  ],
  "acrid": "af8ae790ab06c67e79bb9fadf2d01016",
  "artists": [
    {
      "name": "Imagine Dragons"
    }
  ],
  "trackId": "555694745",
  "streamedCount": 0,
  "listenedCount": 0,
  "userName": "307869-WINDOWS-7044e94d9a96e9526ae929de1049798b227a5c41",
  "playerId": "58c81309e0e7b2cb27dbc450"
}

 


You can mark this as answered now.


Thank you!

You should also be able to use dot.notation to make it cleaner
{ "artists.name" : ["Imagine Dragons"] }

 

Login to post a comment