2

I have a collection with following schema,

        {
                "_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
                "id" : 1,
                "ref" : [
                        {
                                "no" : 101
                        },
                        {
                                "no" : 100
                        }
                        ]
        }

when i tried to push the child Object to ArrayList of Object ,it added into end of array , but my goal is push the object into start index of an array, I tried with this code but it insert the object into end of array failed,

Java code,

            Document push = new Document().append("$push", new Document().append("ref", new Document().append("no", 102)));
            collection.updateMany(new Document().append("id", 1), push);

ExpectedResult should be,

            {
                    "_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
                    "id" : 1,
                    "ref" : [
                            {
                                    "no" : 102
                            },
                            {
                                    "no" : 101
                            },
                            {
                                    "no" : 100
                            }
                            ]
            }
1
  • Care to elaborate what's failing? show the response you are getting? Commented Mar 6, 2017 at 20:47

1 Answer 1

3

Use  $position modifier to specify the location in the array.

Mongodb-Java driver,

ArrayList<Document> docList = new ArrayList<Document>();
docList.add(new Document().append("no", 102));
Document push = new  Document().append("$push", new Document().append("ref", new Document().append("$each", docList).append("$position", 0)));
collection.updateMany(new Document().append("id", 1), push);
Sign up to request clarification or add additional context in comments.

1 Comment

@Ajith happy it's worked for you , You can accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.