我的MongoDB模式是使用如下嵌入式文档构建的:
{
"_id" : ObjectId("5f0c64e4dd0a36b93c7deafa"),
"name" : "Asd",
"email" : "asd@neurondigital.tech",
"password" : "$2b$12$66OTK8mSWELMF5YiF9HMUuHEeOVLI61aINjWs1Cmn1699lLJfz/7y",
"auto_ml" : true,
"notification" : true,
"photo" : null,
"tariff_id" : null,
"city" : null,
"sub_district" : null,
"village" : null,
"latitude" : null,
"longitude" : null,
"created_at" : ISODate("2020-07-13T20:43:00.871+0000"),
"updated_at" : ISODate("2020-07-13T23:08:26.149+0000"),
"family_members" : [
{
"_id" : ObjectId("5f0c98446f0321f6986755d8"),
"name" : "Asd Jr.",
"email" : "asd.jr@neurondigital.tech",
"password" : "$2b$12$K83ScPPb19dtELJs4tc0He9NffE4f9pr9cvjcnpyNoeAUh60cmQXq",
"auto_ml" : true,
"notification" : true,
"photo" : null,
"created_at" : ISODate("2020-07-14T00:22:12.249+0000"),
"updated_at" : ISODate("2020-07-14T00:22:12.249+0000")
},
{
"_id" : ObjectId("5f0c984b6f0321f6986755d9"),
"name" : "Asd Grand Jr.",
"email" : "asd.grandjr@neurondigital.tech",
"password" : "$2b$12$UXfEUGhHf4Hli9oaViirJut.xWAoIWqac6xEdREJKfXq0OVSdGogu",
"auto_ml" : true,
"notification" : true,
"photo" : null,
"created_at" : ISODate("2020-07-14T00:22:19.270+0000"),
"updated_at" : ISODate("2020-07-14T00:22:19.270+0000")
}
],
"rooms" : [
{
"_id" : ObjectId("5f0c98826f0321f6986755da"),
"name" : "Ruang Makan",
"created_at" : ISODate("2020-07-14T00:23:14.839+0000"),
"updated_at" : ISODate("2020-07-14T00:23:14.840+0000"),
"devices" : [
]
},
{
"_id" : ObjectId("5f0c98846f0321f6986755db"),
"name" : "Kamar Mandi",
"created_at" : ISODate("2020-07-14T00:23:16.823+0000"),
"updated_at" : ISODate("2020-07-14T00:23:16.823+0000"),
"devices" : [
]
},
{
"_id" : ObjectId("5f0c98866f0321f6986755dc"),
"name" : "Kamar Tidur Utama",
"created_at" : ISODate("2020-07-14T00:23:18.310+0000"),
"updated_at" : ISODate("2020-07-14T00:23:18.310+0000"),
"devices" : [
]
},
{
"_id" : ObjectId("5f0c98876f0321f6986755dd"),
"name" : "Ruang Tamu",
"created_at" : ISODate("2020-07-14T00:23:19.693+0000"),
"updated_at" : ISODate("2020-07-14T00:23:19.693+0000"),
"devices" : [
]
}
]
}
我想只选择Rooms
字段,按ObjectID降序排序内容,并通过此查询将其限制为1:
db.users.find({'_id': ObjectId("5f0c64e4dd0a36b93c7deafa")}, {'rooms': 1}).sort({'rooms._id': -1}).limit(1)
但是结果不会对字段进行排序,也不会将结果限制为1。我应该使用什么查询来获得期望的输出?
您将无法使用顶级对嵌套数组进行排序或限制。查找
,您可以尝试。聚合
:
db.users.aggregate([
{
$match: { "_id": ObjectId("5f0c64e4dd0a36b93c7deafa") }
},
{
$project: { rooms: 1 }
},
{ $unwind: "$rooms" },
{
$sort: { "rooms._id": -1 }
},
{
$group: {
_id: "$_id",
rooms: { $first: "$rooms" }
}
}
])