Skip to content

Instantly share code, notes, and snippets.

@HellMagic
Created February 25, 2016 06:52
Show Gist options
  • Save HellMagic/4edb27da9adbd3e6761a to your computer and use it in GitHub Desktop.
Save HellMagic/4edb27da9adbd3e6761a to your computer and use it in GitHub Desktop.
mongo用法实例!!!
关于$in操作符的使用,官方有这么描述:
The $in operator selects the documents where the value of a field equals any value in the specified array.注意这里提到"any
value",即如果有document为{qty:[5, 10, 15]},使用db.test.find({qty: {"$in": [10, 1, 3]}})也能找到此document,因为此document的
qty数组对应的值中有一个10在提供的[10, 1, 3]数组中。
示例:db.inventory.find( { qty: { $in: [ 5, 15 ] } } ),等价于 db.invertory.find({"$or":[{qty: 5}, {qty: 15}]}),只不过
当前$or的条件作用的field是同一个field--qty--所以可以使用$in来替代。
$elemMatch的使用
示例:db.scores.find({ results: { $elemMatch: { $gte: 80, $lt: 85 } } })
$elemMatch针对数组里的每一个元素。上述查找的是results中任意一个值满足{$gte: 80, $lt: 85}条件即可。
$eq的使用,{ <field>: { $eq: <value> } }等价于:{ field: <value> },使用此操作符一般是在操作元素的时候,比如配合$elemMatch使用
示例:db.tags.find({tags: {"$elemMatch": {"$eq": '风流'}}}),即查找tags里任意一个元素的值是“风流”的。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment