MongoDB数组查询问题



  • 假设Articles集合的文档结构如下:

    {
       "Author":"ZhangSan",
       "Articles":[
          {
              "Title":"title1",
              "Content":"ABCD12345..",
              "PostTime":"2017-06-10 10:32:05"
          },
          {
              "Title":"title2",
              "Content":"EFGH67890..",
              "PostTime":"2017-06-12 14:23:45"
          }
       ]
    }
    {
       "Author":"Lisi",
       "Articles":[
          {
              "Title":"title3",
              "Content":"ASDFGH..",
              "PostTime":"2017-06-09 11:13:21"
          },
          {
              "Title":"title4",
              "Content":"QWERTY..",
              "PostTime":"2017-06-13 15:08:52"
          }
       ]
    }

    现在要按 {"Title":XXXX, "Author":XXX, "PostTime":XXXXXX } 的格式查询全部文章,并按 PostTime 字段从大到小排序,该如何查询?

  • Lv 1

    @x4_965be

    是個不錯的練習題.

    db.yyy.insertMany([
    {
       "Author":"ZhangSan",
       "Articles":[
          {
              "Title":"title1",
              "Content":"ABCD12345..",
              "PostTime":"2017-06-10 10:32:05"
          },
          {
              "Title":"title2",
              "Content":"EFGH67890..",
              "PostTime":"2017-06-12 14:23:45"
          }
       ]
    },
    {
       "Author":"Lisi",
       "Articles":[
          {
              "Title":"title3",
              "Content":"ASDFGH..",
              "PostTime":"2017-06-09 11:13:21"
          },
          {
              "Title":"title4",
              "Content":"QWERTY..",
              "PostTime":"2017-06-13 15:08:52"
          }
       ]
    }
    ])
    db.yyy.aggregate([
        { $unwind: '$Articles' },
        {
            $project: {
                _id: 0,
                Author: 1,
                Title: '$Articles.Title',
                PostTime: '$Articles.PostTime'
            }
        },
        { $sort: { PostTime: -1 } }
    ]);

登录后回复
 

与 萌阔论坛 的连接断开,我们正在尝试重连,请耐心等待