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

后端 未结 2 1604
不知归路
不知归路 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: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,

提交回复
热议问题