从嵌套数组集合中检索的mongoDB查询 [英] mongoDB query for retrieving from nested array collection
问题描述
{
"_id" : ObjectId("576155a6cd87b68f7e6e42c9"),
"First_Name" : "ok",
"Last_Name" : "jaao",
"Email" : "xyz@gmail.com",
"Sessions" : [
{
"Last_Login" : "Wed, Jun 14, 2016 6:48 PM",
"Class" : "fb",
"ID" : "123"
},
{
"Last_Login" : "Wed, Jun 15, 2016 6:48 PM",
"ID" : "111",
"Class" : "fb"
}
],
"Count" : 2
},
{
"_id" : ObjectId("576155ccf6d8979e7e77df27"),
"First_Name" : "abc",
"Last_Name" : "xyz",
"Email" : "xyz@gmail.com",
"Sessions" : [
{
"Last_Login" : "Wed, Jun 15, 2016 6:49 PM",
"Class" : "fb",
"ID" : "123"
}
],
"Count" : 1
}
这是我的json结构.我想要一个mongoDB查询来检索今天登录的每个用户,即Last_Login
具有今天的日期.
This is my json structure. and I want a mongoDB query which retrieves every user that has logged in today i.e., whose Last_Login
has today's date.
我希望我的输出为:
{
"_id" : ObjectId("576155a6cd87b68f7e6e42c9"),
"First_Name" : "ok",
"Last_Name" : "jaao",
"Email" : "xyz@gmail.com",
"Sessions" : [
{
"Last_Login" : "Wed, Jun 15, 2016 6:48 PM",
"ID" : "111",
"Class" : "fb"
}
],
"Count" : 2
},
{
"_id" : ObjectId("576155ccf6d8979e7e77df27"),
"First_Name" : "abc",
"Last_Name" : "xyz",
"Email" : "xyz@gmail.com",
"Sessions" : [
{
"Last_Login" : "Wed, Jun 15, 2016 6:49 PM",
"Class" : "fb",
"ID" : "123"
}
],
"Count" : 1
}
推荐答案
您将需要聚合.
db.users.aggregate([
{
$unwind: "$Sessions"
},
{
$match: {
"Sessions.Last_Login": {
$gte: ISODate("2016-06-16T00:00:00.0Z"),
$lt: ISODate("2016-06-17T00:00:00.0Z")
}
}
},
{
$group: {
_id: {
_id: "$_id",
First_Name: "$First_Name",
Last_Name: "$Last_Name"
},
Sessions: {
$push: "$Sessions"
}
}
},
{
$project: {
_id: "$_id._id",
First_Name: "$_id.First_Name",
Last_Name: "$_id.Last_Name",
Sessions: "$Sessions"
}
}
])
因此查询将执行以下步骤:
So the query will do those steps:
-
$unwind
所有Sessions
元素
日期范围内的 -
$match
个文档 -
$group
和_id
,First_Name
,Last_Name
一起构成文档
-
$project
文档看起来像原始格式
$unwind
allSessions
elements$match
documents inside the date range$group
together documents by_id
,First_Name
,Last_Name
$project
documents to look like the original format
我省略了一些字段,但是您可以在$group
和$project
步骤中轻松添加它.当然,您需要更改日期范围.
I omitted some fields, but you can easily add it in $group
and $project
steps. And of course you'll need to change the date range.
我担心此查询在一个大集合中的性能.如果您使用我给的第一个查询并过滤代码中想要的会话,也许会更好.
I'm concerned about the performance of this query in a big collection. Maybe is better if you use the first query I gave and filter the sessions you want in your code.
正如@chridam所说,仅当将Last_Login
更改为ISODate()
时,此查询才有效.
As @chridam said, this query will work only if you change Last_Login
to ISODate()
, what is recommended.
更新查询以使用aggregate
并匹配日期范围内仅获取Sessions
的请求.
Updating the query to use aggregate
and match the request of only fetch Sessions
inside the date range.
这是旧版本:
db.users.filter({
'Sessions': {
'$elemMatch': {
'Last_Login': {
'$gte': ISODate("2016-06-16T00:00:00.0Z"),
'$lt': ISODate("2016-06-17T00:00:00.0Z")
}
}
}
})
这篇关于从嵌套数组集合中检索的mongoDB查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!