简体   繁体   中英

mongodb projection matching sub array

I am new to mongodb.I have a mongodb document whose structure is like this :

"prices": {
     "0": {
       "Quantity": {
         "1": "10",
         "2": "14",
         "5": "16",
      },
       "option1": "a4",
       "option2": "50",
       "option3": "qwe",
       "option4": "sdslk" 
    },
     "1": {
       "Quantity": {
         "1": "20",
         "2": "12",
         "10": "3",
      },
       "option1": "a5",
       "option2": "100",
       "option3": "kl",
       "option4": "oiuio" 
    },
     "2": {
       "Quantity": {
         "10": "20",
         "15": "12",
         "100": "3",
      },
       "option1": "a2",
       "option2": "10",
       "option3": "kadl",
       "option4": "qwqw" 
    },
    ...
}

I have an array in PHP like this

Array => ("option1" => "a2",
           "option2"=> "10",
           "option3"=> "kadl",
           "option4"=> "qwqw" 
)

I want to query the document such that it matches a particular sub array in the mongodb doc and return the following result

"2": {
   "Quantity": {
   "10": "20",
   "15": "12",
   "100": "3",
},
"option1": "a2",
"option2": "10",
"option3": "kadl",
"option4": "qwqw" 
}

But only when all the correspoding values (except Quantity match). The options (option1, option2, ...) are different for different documents. Please comment is question is not clear

Not possible since you don't know the name of the key to match to. Perhaps you want prices to actually be an array?

 { "prices" : [{ 
    "Quantity": {
        "10": "20",
        "15": "12",
        "100": "3",
     },
     "option1": "a2",
     "option2": "10",
     "option3": "kadl",
     "option4": "qwqw" 
}] }

Then you can get what you want like this:

db.test.find({ "prices" : { "$elemMatch" : { "option1" : "a2", "option2" : "10", "option3" : "kadl", "option4" : "qwqw" } } }, { "prices.$" : 1 })

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