MongoDB 常用查询语句

1. 条件查询特定数据

db.getCollection('table_name').find({'age':20})

翻译:查询 table_name 表中 age 字段的值等于 20 的所有数据。

2. 条件统计数据总个数

db.getCollection('table_name').find({'age':{'$gte':20}}).count({})

翻译:查询 table_name 表中 age 字段的值大于等于 20 的数据总个数。

3. 在 Go 语言中查询特定范围内的所有符合条件的数据

c := mConn.DB("").C("table_test")

err := c.Find(bson.M{"$and": []bson.M{
        bson.M{"height": bson.M{"$gte": 10}},
        bson.M{"height": bson.M{"$lte": 1000}},
        bson.M{"$or": []bson.M{
            bson.M{"inputs": bson.M{"$elemMatch": bson.M{"address": "aa"}}},
            bson.M{"outputs": bson.M{"$elemMatch": bson.M{"address": "aa"}}},
        }},
    }}).All(&ts)

翻译:查询 table_test 表中 height 字段大于等于 10,并且 height 字段小于等于 1000,并且 inputs 或 outputs 数组中的元素的 address 字段值为 aa 的所有记录详情。

条件查询关键词

等于:    {<key>:<value>}

小于:    $lt

小于或等于: $lte

大于:    $gt

大于或等于: $gte

不等于:   $ne

原文地址:https://www.cnblogs.com/wf-l5201314/p/12201570.html