如何获取数组mongodb中的字段值

时间:2017-05-23 08:46:43

标签: mongodb mongodb-query aggregation-framework

假设我的数据库结构为;

public class ThreadStarterTest {

    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(1);

        SyncedThread thread1 = new SyncedThread(latch, "thread 1") {
            @Override
            public void run() {
                try {
                    System.out.println(getName() + " running");
                    Thread.sleep(2_000);
                    latch.countDown();
                    Thread.sleep(3_000);
                    System.out.println(getName() + " finished");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };


        SyncedThread thread2 = new SyncedThread(latch, "thread 2") {
            @Override
            public void run() {
                try {
                    latch.await();
                    System.out.println(getName() + " running");
                    Thread.sleep(5_000);
                    System.out.println(getName() + " finished");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        try {
            thread2.start();
            Thread.sleep(500);
            thread1.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static class SyncedThread extends Thread {
        private final CountDownLatch latch;

        public SyncedThread(final CountDownLatch latch, final String name) {
            super(name);
            this.latch = latch;
        }
    }

}

我想要做的是获取每个名字的学校名称

{
    name: "alex",
    age: 21,
    school: [
       {grade: 45, class: "elementary school", name: "blabla"},
       {grade: 89, class: "high school", name: "blabla2"},
       {grade: 12, class: "college", name: "blabla3"}
    ]
},
{
    name: "felix",
    age: 45,
    school: [
       {grade: 12, class: "elementary school", name: "bla"},
       {grade: 45, class: "high school", name: "bla2"},
       {grade: 16, class: "college", name: "bla3"}
    ]
}

为了实现这一目标,

{
    name: alex,
    school: ["blabla", "blabla2", "blabla3"]
},
{
    name: felix,
    school: ["bla", "bla2", "bla3"]
}

但无法实现。我应该修改什么?

1 个答案:

答案 0 :(得分:1)

在使用 school 这一阶段进行分组之前,只需取消$unwind数组的取消:

db.collection.aggregate([
  {$unwind: "$school"},
  {$group: {_id: "$name", school: {$addToSet: "$school.name"}}}
])

输出:

{ "_id" : "felix", "school" : [ "bla3", "bla2", "bla" ] }
{ "_id" : "alex", "school" : [ "blabla3", "blabla2", "blabla" ] }