user3190153
user3190153

Reputation: 39

How to write a mongo query that queries an array?

Say I have a mongo database that stores the below data

String | Array
ID     | Data
100    | [Name: John, Age: 5]
100    | [Name: Lucy, Age: 5]
200    | [Name: Pete, Age: 5]
200    | [Name: Andy, Age: 5]
200    | [Name: Jimi, Age: 5]
300    | [Name: Raul, Age: 5]

How do I query the database to give me all the ID's and their existing Names within Data. I would expect the result to be showing only the two columns I need, as below:

{
    "ID" : "100", "Data" : [ "Name" : "John"]
    "ID" : "100", "Data" : [ "Name" : "Lucy"]
    "ID" : "200", "Data" : [ "Name" : "Pete"]
    "ID" : "200", "Data" : [ "Name" : "Andy"]
    "ID" : "200", "Data" : [ "Name" : "Jimi"]
    "ID" : "300", "Data" : [ "Name" : "Raul"]
}

Upvotes: 0

Views: 39

Answers (1)

FallAndLearn
FallAndLearn

Reputation: 4135

db.collection_name.find(
   {},
   { "ID": 1, "Data.name": 1 }
)

It doesn't look like an array to me and it's probably an object. You can use above query which will show the columns which are set to 1.

Upvotes: 2

Related Questions