Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

mongodb - How to exclude from search results documents with fields which are not present in query?

I have two documents:

  1. { p1:"a", p2:"b" }
  2. { p1:"a", p2:"b", p3:"c" }

What I should to do with query: { p1:"a", p2:"b" } to find only first document? So I want find only documents with fields what I specified. If document has more fields (than query) it should not be presented in search results.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I must admit I know of no normal querying method by which to solve this problem. There is only one way I know of and that is to use MongoDBs object comparison. To do this you would change your structure to be something along the lines of:

{
    ps: [a,b]
}

or:

{
    ps: {p1:a,p2:b}
}

And then you would query like:

db.col.find({ p: [a,b] })

or:

db.col.find({ p: {p1:a, p2:b} })

There is one immedate problem with this though. It is key order dependant which means that if your a and b are actually the other way around in another document it won't match. So you will need to make sure you care about order when saving if you do this.

Hope it helps,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...