1

I am new to MongoDB, I want to remove an element from array structure as shown below:

{
    "Data" : [
        {           
            "url" : "www.adf.com"
            "type":7
        },
        {

            "url" : "www.pqr.com"
            "type":2
        }
        {           
            "url" : "www.adf.com"
            "type":3
        },
        {

            "url" : "www.pqr.com"
            "type":5
        }
    ],

}

I want to remove url=www.adf.com which has type as lowest values i.e in this document my query should remove type=3 and return document as below:

{
        "Data" : [
            {           
                "url" : "www.adf.com"
                "type":7
            },
            {

                "url" : "www.pqr.com"
                "type":2
            }

            {

                "url" : "www.pqr.com"
                "type":5
            }
        ],

    }
0

2 Answers 2

1

The query shown by @shakthydoss can be described in java as follows:

    MongoClient mongoClient = new MongoClient("SERVER", 27017);
    DB db = mongoClient.getDB("DB_NAME");
    DBCollection coll1 = db.getCollection("COLLECTION_NAME");
    DBObject eleMatch = new BasicDBObject();
    eleMatch.put("url", "www.pqr.com");
    eleMatch.put("type", new BasicDBObject("$lte", 50));
    BasicDBObject up = new BasicDBObject();
    up.put("$elemMatch", eleMatch);
    BasicDBList basicDBList = new BasicDBList();
    basicDBList.add(up);
    DBObject query = new BasicDBObject("Data", new BasicDBObject(" $all", basicDBList));
    coll1.find(query);
Sign up to request clarification or add additional context in comments.

Comments

0

Use $all with $elemMatch

If the field contains an array of documents, you can use the $all with the $elemMatch operator.

db.inventory.find( {
                 Data: { $all: [
                                { "$elemMatch" : { url : "www.pqr.com": "M", type: { $lte: 50} } },

                              ] }
               } )

3 Comments

i need in java not in mongo shell
If you dont know the value ($lte: 50) to be compared then use map reduce approach to find the array element.
Can past what your java snippet that you have tried so far. Let me see if I can help you.

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.