MongoDB的过滤器是否有“$ slice”比较?

时间:2016-01-14 11:13:27

标签: mongodb mongodb-query

在MongoDB中有一个projection operator $slice,它允许投射一个子阵列。

有没有办法按数组切片过滤?类似的东西:

db.testdb.find( {arrayofstring: { $eqSlice: {$slice: [0,1], $val: [ "a" ] } } }, {...})

编辑一个示例及其预期输出

> db.studentsTestDataTypes.find({},{ _id: 1, int: 1, arraystring: 1})

{ "_id" : ObjectId("56977186756088b586154f9d"), "int" : 2001, "arraystring" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("56977186756088b586154f9e"), "int" : 2002, "arraystring" : [ "d", "e", "f" ] }

预期结果示例:在arraystring的第一个位置按值“a”的条目进行过滤:

{ "_id" : ObjectId("56977186756088b586154f9d"), "int" : 2001, "arraystring" : [ "a", "b", "c" ] }

1 个答案:

答案 0 :(得分:1)

假设您的收藏中包含以下文档:

{ "_id" : ObjectId("56977186756088b586154f9d"), "int" : 2001, "arraystring" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("56977186756088b586154f9e"), "int" : 2002, "arraystring" : [ "d", "e", "f" ] }
{ "_id" : ObjectId("56978e21ae9bb55c0d7cdc67"), "int" : 2001, "arraystring" : [ "b", "a", "c" ] }

更简单,最好的方法是使用dot notation

db.collection.find({ "arraystring.0": "a" } )

哪个收益率:

{
        "_id" : ObjectId("56977186756088b586154f9d"),
        "int" : 2001,
        "arraystring" : [
                "a",
                "b",
                "c"
        ]
}