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
268 views
in Technique[技术] by (71.8m points)

MongoDB: Find Subdocument in Array Matching Parameters

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

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

1 Answer

0 votes
by (71.8m points)

You want to use $elemMatch.

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

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

...