Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mongodb - find the document from sub array?

I have a collection with documents that look like this:

"awards" : {
    "oscars" : [
        {"award": "bestAnimatedFeature", "result": "won"},
        {"award": "bestMusic", "result": "won"},
        {"award": "bestPicture", "result": "nominated"},
        {"award": "bestSoundEditing", "result": "nominated"},
        {"award": "bestScreenplay", "result": "nominated"}
    ],
    "wins" : 56,
    "nominations" : 86,
    "text" : "Won 2 Oscars. Another 56 wins and 86 nominations."
}

What query document would we use in a find() command to return all movies in the my_collection collection that either won or were nominated for best picture?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use the dot notation to specify an exact match on the embedded document and use the $in operator to select those documents that won or were nominated for best picture

You shouldn't use the $or operator here because it will perform a collection scan if not all the clauses are supported by indexes as mention in the documentation.

db.my_collection.find({ 
    'awards.oscars.award': 'bestPicture', 
    'awards.oscars.result': { '$in': [ 'won', 'nominated' ] } 
} )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...