Multiple limit condition in mongodb

后端 未结 2 1737
清酒与你
清酒与你 2021-01-27 10:47

I have a collection in which one of the field is \"type\". I want to get some values of each type depending upon condition which is same for all the types. Like I want 2 documen

2条回答
  •  情歌与酒
    2021-01-27 11:19

    You will not be able to do this directly with only the type column and the constraint that it must be one query. However there is (as always) a way to accomplish this.

    To find documents of different types, you would need to have some type of additional value that, on average distributed the types out according to how you want the data back.

    db.users.insert({type: 'A', index: 1})
    db.users.insert({type: 'B', index: 2})
    db.users.insert({type: 'A', index: 3})
    db.users.insert({type: 'B', index: 4})
    db.users.insert({type: 'A', index: 5})
    db.users.insert({type: 'B', index: 6})
    

    Then when querying for items with db.users.find(index: {$gt: 2, $lt: 7}) you will have the right distribution of items.

    Though I'm not sure this was what you were looking for

提交回复
热议问题