Search code examples
javamongodbmongo-javamongo-jackson-mappermongojack

MongoDB - MongoJack find and remove


I am completely new to MongoDB and MongoJack.

I have this collection called pbf

{
            "_id" : ObjectId("541ea72044ae1b4043e9ccba"),
            "name" : "First civ game",
            "type" : "WAW",
            "numOfPlayers" : 4,
            "active" : true,
            "players" : [ ],
            "civs" : [
                    {
                            "objectType" : "civ",
                            "name" : "Indians",
                            "used" : false,
                            "hidden" : true
                    },
                    {
                            "objectType" : "civ",
                            "name" : "Arabs",
                            "used" : false,
                            "hidden" : true
                    },
                    {
                            "objectType" : "civ",
                            "name" : "Japanese",
                            "used" : false,
                            "hidden" : true
                    },
                    {
                            "objectType" : "civ",
                            "name" : "Egyptians",
                            "used" : false,
                            "hidden" : true
                    },
}

What I want to do "Remove and return one civs item by Id"

I have tried something like this:

    protected static JacksonDBCollection<PBF, String> pbfCollection;

    BasicDBObject field = new BasicDBObject();
    field.put("civs", 1); 
    field.put("_id", "541ea72044ae1b4043e9ccba");
    PBF pbf = pbfCollection.findAndRemove(field)

But this just throws exception saying it doesn't find anything

So bascially I want this returned

                    {
                            "objectType" : "civ",
                            "name" : "Indians",
                            "used" : false,
                            "hidden" : true
                    }

How can I accomplish this?


Solution

  • I solved it using two steps. I am sure though there is a better way of doing it.

    //First get, then remove, then update
    
    PBF pbf = pbfCollection.findOneById(pbfId);
    Civ civ = pbf.getCivs().remove(0);
    pbfCollection.updateById(pbf.getId(), pbf);
    

    This worked, but I think it should be a better way of doing it