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

Categories

In MongoDB I would like to find a document based on the values of a subdocument meeting certain parameters. Specifically I have a document structured like this:

{
  name: "test",
  data: [{
    name: "test1",
    start: 0,
    end: 2
  },
  {
    name: "test2",
    start: 15
    end: 18
  }]
}

How can I tell MongoDB to only return my document if the start time for a data subdocument is less than 5 and the end time for the same subdocument is greater than 5? Currently, if I do

db.foo.findOne({
  'data.start': { $lte: 5 },
  'data.end': { $gte: 5 }
})

it will return my document always because 5 is greater than 0 and less than 18. How can I tell MongoDB to only return my document if 5 (or whatever value) is greater than 0 and less than 2 OR greater than 15 and less than 18?

question from:https://stackoverflow.com/questions/11823296/mongodb-find-subdocument-in-array-matching-parameters

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

1 Answer

You want to use $elemMatch.

db.foo.findOne({ data: { $elemMatch : {
  start: { $lte: 5 },
  end: { $gte: 5 }
  }}
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...