简体   繁体   中英

MongoDb, NodeJs - How to find a document by searching it by id of an array element

This is my Model:-

   "_id":{
      "$oid":"5f0dbca73ef98355649d7cc7"
   },
   "name":"Multiple Image test",
   
   "description":"Awesome",
   
   "price":{
      "$numberInt":"15000"
   },
   "images":[
      {
         "_id":{
            "$oid":"5f0dbca73ef98355649d7cc9"
         },
         "data":{
            "$binary":{
               "base64":"random buffer data",
               "subType":"00"
            }
         },
         "contentType":"image/jpeg"
      },
      {
         "_id":{
            "$oid":"5f0dbca73ef98355649d7cc8"
         },
         "data":{
            "$binary":{
               "base64":"Random buffer data",
               "subType":"00"
            }
         },
         "contentType":"image/jpeg"
      }
   ],
   
   
}
      
    

Now how can i access a particular image data from the images field?

I am using mongoose js so which query can be used and how to use it to access the data. Any kind of help would be appreciated.

And to boil Asiri's comment into something that fits your case: You use the $elemMatch operator: https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

MyModel.find({'images': {$elemMatch: {_id: ObjectId("5f0dbca73ef98355649d7cc8")}}}

You might not need the cast to ObjectId. (Now you should be able to guess that I haven't tested this answer, and for that I'm profoundly sorry.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM