gpt4 book ai didi

mongodb - 在 MongoDb 中,如何对文档中存在的内部字段进行排序?

转载 作者:可可西里 更新时间:2023-11-01 10:44:25 25 4
gpt4 key购买 nike

我的文档是这样的

{
field1: somevalue,
name:xtz


nested_documents: [ // array of nested document
{ x:"1", y:"2" }, // first nested document
{ x:"2", y:"3" }, // second nested document
{ x:"-1", y:"3" }, // second nested document
// ...many more nested documents
]
}

如何对 nested_documents 中的数据进行排序?
预期答案如下所示:

nested_documents: [ { x:"-1", y:"3" },{ x:"1", y:"2" },{ x:"2", y:"3" }]

最佳答案

为此,您必须使用聚合框架

db.test.aggregate([{$unwind:'$nested_documents'},{$sort:{'nested_documents.x': 1}}])

返回

"result" : [
{
"_id" : ObjectId("5139ba3dcd4e11c83f4cea12"),
"field1" : "somevalue",
"name" : "xtz",
"nested_documents" : {
"x" : "-1",
"y" : "3"
}
},
{
"_id" : ObjectId("5139ba3dcd4e11c83f4cea12"),
"field1" : "somevalue",
"name" : "xtz",
"nested_documents" : {
"x" : "1",
"y" : "2"
}
},
{
"_id" : ObjectId("5139ba3dcd4e11c83f4cea12"),
"field1" : "somevalue",
"name" : "xtz",
"nested_documents" : {
"x" : "2",
"y" : "3"
}
}
],
"ok" : 1

希望对你有帮助

关于mongodb - 在 MongoDb 中,如何对文档中存在的内部字段进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15291318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com