如何在MongoDB中检索对象内的不同键

时间:2017-04-22 11:42:31

标签: arrays mongodb mongodb-query

我在MongoDB中有这个:

{ "_id" : ObjectId("58fb35531eb5df245d5d434f"), "name" : "d1.html", "indexation" : { "Citroen" : 1, "color" : 1, "Marca" : 1, "rojo" : 1 } }
{ "_id" : ObjectId("58fb35531eb5df245d5d4350"), "name" : "d2.html", "indexation" : { "blancos" : 1, "ocasión" : 1, "Madrid" : 1, "Coches" : 1, "rojo" : 1, "coches" : 1 } }
{ "_id" : ObjectId("58fb35531eb5df245d5d4351"), "name" : "d3.html", "indexation" : { "rojos" : 1, "Ocasión" : 1, "marcas" : 1, "Madrid" : 1, "blancas" : 1, "autos" : 1, "de" : 1 } }

您可以看到包含上述内容的图片:Content

我想在每个文档中的对象“索引”中获取不同的键。 我想得到的结果是:["Citroen", "color", "Marca", "rojo", "blancos", "ocasión", "Madrid", "Coches", "coches", "rojos", "Ocasión", "marcas", "blancas" "autos", "de"]

我正在尝试使用distinct(“indexation”),但我得到了整个索引...

你能告诉我,为了得到我想要的东西,我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以在$objectToArrray版本中使用新的3.4.4转换所有密钥&值对文档数组后跟$unwind& $group $addToSet db.collection.aggregate([{$project: {indexation: {$objectToArray: "$indexation"}}}, {$unwind:"$indexation"}, {$group:{_id:null, keys:{$addToSet:"$indexation.k"}}}]) 获取不同的密钥

indexation

对于较低版本,您可以将db.collection.distinct("indexation.k")更新为如下所示并使用

{ "_id" : ObjectId("58fb35531eb5df245d5d434f"), "name" : "d1.html", "indexation" : [{ "k" : "Citroen", "v" : 1 }, { "k" : "Marca", "v" : 1 }]}

import java.util.ArrayList;
import java.util.Scanner;

public class Main1 {
    public static int processArray(ArrayList<Integer> array) {

        int sum = 0;
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) % 2 == 0) {
                sum += array.get(i);
                array.remove(i);
            }
        }
        return sum;
}

    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int num = in.nextInt();
            if (num < 0)
                break;
            arrayList.add(new Integer(num));
        }
        int sum = processArray(arrayList);
        System.out.println("Sum of even index numbers " + sum);
        for (int i = 0; i < arrayList.size(); i++)
            System.out.println(arrayList.get(i));
    }
}