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

后端 未结 2 1600
不知归路
不知归路 2020-12-11 13:22

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

相关标签:
2条回答
  • 2020-12-11 13:57

    It's not easy to do with that structure, you need some other indexable cue as to what to take and to leave.

    If you know what fields you DON'T want, you can use $exists, http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists but it's not very efficient.

    db.col.find({p3:{$exists:false}})
    

    You could also just do this;

    db.col.find({ p1:"a", p2:"b", p3:null }
    

    Could you just throw away the fields you don't want in your own code? Or could you restructure into nested groups to make it easier to filter?

    { basicData:{p1:"a", p2:"b"}, extraData:{p3:"c",p4:"d"} }
    
    0 讨论(0)
  • 2020-12-11 13:59

    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,

    0 讨论(0)
提交回复
热议问题