简体   繁体   中英

How to search for a match on values in whle document and all subdocuments in MongoDB?

I have a mongo database with a collection named store.

db.store.find() on mongo shell yields the below.

{ "_id" : ObjectId("575d6fab0cde6714290f444f"), "train" : "a", "data" : { "0" : { "this" : 21, "that" : 31, "value" : 11, "month" : 1 }, "3" : { "this" : 21, "that" : 34, "value" : 14, "month" : 2 } } }
{ "_id" : ObjectId("575d6fab0cde6714290f4450"), "train" : "b", "data" : { "1" : { "this" : 22, "that" : 32, "value" : 12, "month" : 2 }, "4" : { "this" : 25, "that" : 35, "value" : 15, "month" : 1 } } }
{ "_id" : ObjectId("575d6fab0cde6714290f4451"), "train" : "c", "data" : { "2" : { "this" : 22, "that" : 33, "value" : 13, "month" : 1 }, "5" : { "this" : 26, "that" : 36, "value" : 16, "month" : 2 } } }

I want to search for all of document/subdocument/field matching certain keys/values in the document.

How should I be searching the document so that the resulting document searching for {'this': 22} would be as below.

{ "_id" : ObjectId("575d6fab0cde6714290f4450"), "train" : "b", "data" : { "1" : { "this" : 22, "that" : 32, "value" : 12, "month" : 2 }, "4" : { "this" : 25, "that" : 35, "value" : 15, "month" : 1 } } }
{ "_id" : ObjectId("575d6fab0cde6714290f4451"), "train" : "c", "data" : { "2" : { "this" : 22, "that" : 33, "value" : 13, "month" : 1 }, "5" : { "this" : 26, "that" : 36, "value" : 16, "month" : 2 } } }

Similarly searching for {'this': 21} would return below.

{ "_id" : ObjectId("575d6fab0cde6714290f444f"), "train" : "a", "data" : { "0" : { "this" : 21, "that" : 31, "value" : 11, "month" : 1 }, "3" : { "this" : 21, "that" : 34, "value" : 14, "month" : 2 } } }

I understand db.store.find({'data.0.this':21}) would also result in the same result as above for {'this': 21} , but that is not what I am looking at here, as I would not know where under the field data would the field document with the field this be. It could be data.0 or data.1 or data.2 .

The way you structured your document, you won't be able to make the sort of queries you'd like to. I'd assumed the embedded documents were in an array. But what you have is a single embedded document.

If you changed your document structure to have the data key be an array of stub documents, then you could make queries like the following:

 db.store.find({'data.this':21}) 

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