Помогите с запросом по sub документу

21 views
Skip to first unread message

Denis Volokh

unread,
Aug 21, 2015, 5:47:05 AM8/21/15
to MongoDB по-русски
Добрый день,

У меня есть следующая структура документа:
{
    "_id": ObjectId("55d6d1ed54ac98ad306f6a2b"),
    "position_id": ObjectId("55d6d1ed54ac98ad306f6a2a"),
    "changes": {
        "1": {
            "name": "init"
        },
        "2": {
            "name": "Test"
        },
        "3": {
            "total": "100",
            "realized": "400"
        },
        "4": {
            "total": "101",
            "realized": "405"
        }
    }
}

где 1,2,3,4,5 - timestamp.

Я хочу к примеру получить все changes с timestamp от 2 до 3. 

Спасибо.

Денис Захаров

unread,
Aug 21, 2015, 5:55:06 AM8/21/15
to mongodb-us...@googlegroups.com
А в чем вообще смысл хранить значения, по которым нужно что-то искать, в качестве имен свойств объекта changes? Я бы с этого начал, а там, глядишь, ответ найдется сам собой.

--
You received this message because you are subscribed to the Google Groups "MongoDB по-русски" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user-rus...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Denis Volokh

unread,
Aug 21, 2015, 6:08:34 AM8/21/15
to MongoDB по-русски
Согласен, переделал немного структуру:

    "_id" : ObjectId("55d6d1ed54ac98ad306f6a2b"), 
    "position_id" : ObjectId("55d6d1ed54ac98ad306f6a2a"), 
    "changes" : [
        {
            "timestamp" : "1", 
            "fields" : [

            ]
        }, 
        {
            "timestamp" : "2", 
            "fields" : [

            ]
        }, 
        {
            "timestamp" : "3", 
            "fields" : [

            ]
        }, 
        {
            "timestamp" : "4", 
            "fields" : [

            ]
        }
    ]
}

Теперь я делаю запрос следующим образом:

{
    "changes": {
        $elemMatch : {
            "timestamp" : {
                $gte : 2
            }
        }
    }
}

Но в результате просто весь документ.


Денис Захаров

unread,
Aug 21, 2015, 6:14:02 AM8/21/15
to mongodb-us...@googlegroups.com
В результате поиска так или иначе все равно получится документ (со всеми полями или нет). Если нужно искать именно вложенные документы - храните их в отдельной коллекции

Denis Volokh

unread,
Aug 21, 2015, 6:27:22 AM8/21/15
to mongodb-us...@googlegroups.com
Не понял на счёт отдельной коллекции, можешь пояснить?
You received this message because you are subscribed to a topic in the Google Groups "MongoDB по-русски" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mongodb-user-russian/kEbUydWC0p0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mongodb-user-rus...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.


--
Kind regards,
Denis Volokh

Денис Захаров

unread,
Aug 21, 2015, 6:33:32 AM8/21/15
to mongodb-us...@googlegroups.com
В отдельной коллекции changes хранить объекты с полями timestamp, fields, position_id, к примеру. Вариантов масса. Зависит от бизнес-логики.

21 августа 2015 г., 13:27 пользователь Denis Volokh <denis....@gmail.com> написал:

Denis Volokh

unread,
Aug 21, 2015, 6:37:51 AM8/21/15
to mongodb-us...@googlegroups.com
А с моей структурой данных есть вариант запроса который вернет только указанные элементы массива changes?

Денис Захаров

unread,
Aug 21, 2015, 6:42:16 AM8/21/15
to mongodb-us...@googlegroups.com
я не припомню такого, может где-то в доках зарыто

21 августа 2015 г., 13:37 пользователь Denis Volokh <denis....@gmail.com> написал:

Vladimir Mukhin

unread,
Aug 21, 2015, 11:22:29 AM8/21/15
to mongodb-us...@googlegroups.com
Aggregation framework вам поможет.

Допустим: 

> db.test.find().pretty()

{

"_id" : ObjectId("55d74133823f1a5bc1f02ed1"),

"changes" : [

{

"timestamp" : 1,

"fields" : [ ]

},

{

"timestamp" : 2,

"fields" : [ ]

},

{

"timestamp" : 3,

"fields" : [ ]

}

]

}

{

"_id" : ObjectId("55d74143823f1a5bc1f02ed2"),

"changes" : [

{

"timestamp" : 2,

"fields" : [ ]

},

{

"timestamp" : 3,

"fields" : [ ]

},

{

"timestamp" : 4,

"fields" : [ ]

}

]

}


Тогда: 

> db.test.aggregate([

   { $unwind: '$changes' },

   { $match: { 'changes.timestamp': { $gte: 2 } } }

])

{ "_id" : ObjectId("55d74133823f1a5bc1f02ed1"), "changes" : { "timestamp" : 2, "fields" : [ ] } }

{ "_id" : ObjectId("55d74133823f1a5bc1f02ed1"), "changes" : { "timestamp" : 3, "fields" : [ ] } }

{ "_id" : ObjectId("55d74143823f1a5bc1f02ed2"), "changes" : { "timestamp" : 2, "fields" : [ ] } }

{ "_id" : ObjectId("55d74143823f1a5bc1f02ed2"), "changes" : { "timestamp" : 3, "fields" : [ ] } }

{ "_id" : ObjectId("55d74143823f1a5bc1f02ed2"), "changes" : { "timestamp" : 4, "fields" : [ ] } }



-- 
Vladimir Mukhin @ MongoDB

Denis Volokh

unread,
Aug 24, 2015, 1:05:35 AM8/24/15
to MongoDB по-русски
Спасибо, как раз то что надо.


Reply all
Reply to author
Forward
0 new messages