开发者

Setting individual bits in mongo, to store a bitmask

开发者 https://www.devze.com 2023-04-01 05:43 出处:网络
I want to store some flags into a mongo db. For now I have the following: > db.test.save({a:0x1}) > db.test.save({a:0x3})

I want to store some flags into a mongo db. For now I have the following:

> db.test.save({a:0x1})
> db.test.save({a:0x3})
> db.test.save({a:0x2})
> db.test.save({a:0x2})
> db.test.save({a:0x4})
> db.test.save({a:0x5})
> db.test.find({'$where': "this.a &开发者_StackOverflow中文版 0x1"})

Is there a more effective way?


While you can do it that way, I'd suggest using separate boolean fields for each flag. That will take up more space but will be faster to query because it won't use javascript and can use indexes if needed. If you need the bitfield for other parts of your application you can keep them both up to date like this (assuming a,b,c... map to bits 0,1,2...):

db.c.update({_id:ID}, {$set:{a:true}, $bit:{bits: {or: 0x1}}})
db.c.update({_id:ID}, {$set:{c:false}, $bit:{bits: {and: ~0x8}}})


when your use $where:"this.myField & 0x1" it is same as $where:"0" and $where:"1" and this is wrong because 0 == false = true, but 0 === false = false

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号