0

I have a mongo DB with that kind of objects:

{
    "_id" : ObjectId("5d67e5b75f99ee4d8c996624"),
    "metadata" : {
        "ownerEmail" : "test@test.com",
        "firmwareVersion" : "01",
        "hardwareId" : "00001"
    },
    "serialnumber" : "automate01",
}

In javascript, i use that kind of call to get all the objects of the collections, and that works:

  getAll(): Promise<Automate[]> {
    return this.database
      .collection('automates')
      .find({})
      .toArray();
  }

but when i want to select object by 'ownerEmail' i write something like:

    getAllByUser(email: string): Promise<Automate[]> {
    return (
      this.database
        .collection('automates')
        .find({
          metadata: {
            ownerEmail: email
          }
        })
        .toArray()
    );
  }

This return nothing... so, what am i doing wrong. I read this:https://docs.mongodb.com/manual/tutorial/query-embedded-documents/ And... i did the same as described. Any help ?

user3178486
  • 321
  • 6
  • 17
  • Possible duplicate of [How to query nested objects?](https://stackoverflow.com/questions/16002659/how-to-query-nested-objects) – str Sep 07 '19 at 12:54

1 Answers1

1

You are using object so it is simple to write

 getAllByUser(email: string): Promise<Automate[]> {
    return (
      this.database
        .collection('automates')
        .find({ "metadata.ownerEmail": email })
        .toArray()
    );
  }

But if you are using array of object or array of array then you need to use $elemMatch Like this type of data

{
    "_id" : ObjectId("XXXXXXXXXXXXXXXXXXX"),
    "metadata" : [ 
        {
            "ownerEmail" : "test@test.com",
            "firmwareVersion" : "01",
            "hardwareId" : "00001"
        }
    ],
    "serialnumber" : "automate01"
}

which become

.find({ "metadata" :{ $elemMatch : { "ownerEmail": "test@test.com" }}})
Ashok
  • 2,846
  • 1
  • 12
  • 20