Insert Array inside an object in MongoDB

后端 未结 3 738
悲哀的现实
悲哀的现实 2021-02-05 12:11

I am new at MongoDB and I want to insert to mongodb data like this but I couldn\'t figure out how

{
  image = \"cab\"
  tags = [
            [ \"NNP\", 0 ],
             


        
3条回答
  •  半阙折子戏
    2021-02-05 13:06

    Here is how i use it when using mongo3.x:

    suppose you want the result to be like this: {"data": [{"key":"v1"}, {"key":"v1"}, {"key":"v1"}] }

    [step1]: use Java Map to create json object which maps to the elements inside the array; that is, the {} inside []

    [step1 Ans]: Map m1,m2,m3 = new HashMap(); m1.put("key", "v1"); m2.put("key", "v1"); m3.put("key", "v1");

    [step2]: use Java List to add all Java Map into one element.

    [step2 Ans]: List list = new ArrayList(); list.add(m1); list.add(m2); list.add(m3);

    [step3]: add Java list into mongo

    [step3 Ans]: Document dc = new Document("key", list);

提交回复
热议问题