V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
hiwljun
V2EX  ›  MongoDB

mongodb如何对内嵌的文档进行排序?

  •  
  •   hiwljun · 2013-11-28 07:36:17 +08:00 · 8189 次点击
    这是一个创建于 3800 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想对评论的查询结果按更新时间倒序显示。
    {
    comment:
    [
    {
    "author":"mongodb",
    "content":"排序",
    "datetime":2013-11-28
    },
    {
    "author":"mongodb",
    "content":"排序",
    "datetime":2013-11-29
    },
    {
    "author":"mongodb",
    "content":"排序",
    "datetime":2013-11-30
    }
    ]
    }
    10 条回复    1970-01-01 08:00:00 +08:00
    lichao
        1
    lichao  
       2013-11-28 07:51:50 +08:00
    lichao
        2
    lichao  
       2013-11-28 08:29:14 +08:00
    @lichao 哦,内嵌的数组不是这样排
    hiwljun
        3
    hiwljun  
    OP
       2013-11-28 09:08:13 +08:00
    @lichao 嗯,估计只要在结果里用python去排了。
    1to3
        4
    1to3  
       2013-11-28 11:16:34 +08:00 via Android
    db.collection.find(criteria).sort({comment.datetime:-1})
    猜的。
    hiwljun
        5
    hiwljun  
    OP
       2013-11-28 13:58:44 +08:00
    @1to3 find_one的时候就不可用了。
    1to3
        6
    1to3  
       2013-11-28 14:02:18 +08:00 via Android
    db.collection.find(criteria).sort({comment.datetime:-1}).limit(1) 这个?
    1to3
        7
    1to3  
       2013-11-28 17:31:07 +08:00 via Android
    @hiwljun find 或者findOne应该是不改变文档数据的,你说到的情况,已经对文档内部数据结构修改了,先update排好序再find,或者把comment放到另一个collection,或者就如你说的先查到数据再在应用层面去排序。
    不好意思一开始没看明白你的意思。
    hiwljun
        8
    hiwljun  
    OP
       2013-11-28 19:14:27 +08:00
    @1to3 嗯,find_one返回的是一个字典,所以不能使用sort(),update的时候好像不能排序。现在的解决方法还是使用应用层面去排序了。
    mahone3297
        9
    mahone3297  
       2013-11-28 20:40:39 +08:00
    @hiwljun 如果数据量很大,需要全拿出来在应用层去排序?那不是疯了?
    当然,我也不懂mongodb。但是我猜应该是有排序吧?
    1to3
        10
    1to3  
       2013-12-04 11:21:32 +08:00 via Android   ❤️ 1
    db.blog.aggregate({$unwind: "$comments"}, {$sort: {comments.datetime: -1}})
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3484 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:58 · PVG 12:58 · LAX 21:58 · JFK 00:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.