3

Hi I have some trouble with arrays in mongodb. To read a document with java is no problem but to read an array what is in a document is a problem. Lets say I have a collection myCol:

{"name": "lenny linux", "gender": "m", "computers": [{"name": "computer"}, {"name": "computer2"} {"name"...}]}

So there is an array with computers. I could read the whole document with

        DBCollection myCol = getCollection(...);
        BasicDBObject query = new BasicDBObject();
        query.put(name, "lenny linux");

        DBCursor cursor = myCol.find(query);
        while (cursor.hasNext()) {
            System.out.print(cursor.next());
        }

But I just need the names of the computers, so I have to read somehow the array. Dont get this array stuff in mongodb. And also what if I would like to delete something from a mongodb array? Its not the same as to delete a normal document... thank you for any help!

Edit: If im reading the mongodb page: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray I really dont get it. They have there an array of colors and then they are reading red like this:

db.things.find({ colors :"red" });

Why would I do this? If I want to read an array to know whats inside the array. The user dont know that there is a "red" or blue or whatever. Maybe the array colors is empty? Then I get back a null, 0 or whatever and if there are 4 colors then give me these colors, print it out. I dont have any other examples...im sorry for my bad english.

Edit2: Ok so the new solution for me is to get the whole document where name == lenny linux (like at the first time in my code) and then to parse this document with an extern JSON parser like json-simple. Well maybe thats not the best solution, because the best solution would be to get the stuff in the array without other libs just using the mongolib... but ok its working :) If somebody knows an easier way just post it here. Thank you.

8
  • if Im doing this Im getting back a whole document with id, name, gender and everything. But I would like to only get the names in the array. So a System.out.print(myFunctionToReadComputersFrom("lenny linux") should print out: computer, computer2, ... Commented Jan 22, 2012 at 18:30
  • 1
    that's how mongodb works, it stores documents and let's you query for documents. if you want a piece of information from a document, you have to pull it out. Commented Jan 22, 2012 at 19:51
  • so there is a big big doc what I get returned and because I just need the array part I have to build a regex (or something else?) to get the stuff in the array? Commented Jan 22, 2012 at 19:55
  • you don't have to fetch the whole document, you can selectively pick out fields you want returned. remember, you're the one deciding on the document schema, so why would you create a huge doc if you only need one or two fields? Commented Jan 22, 2012 at 20:09
  • pick out fields? I think I missed something, could you please make an example? ^^ Commented Jan 22, 2012 at 20:14

4 Answers 4

1

And also what if I would like to delete something from a mongodb array? Its not the same as to delete a normal document.

http://www.mongodb.org/display/DOCS/Updating explains 2 ways:

  • $set: to replace the current array with a new one (fetch the previous array, remove an element or two, and update with $set)

  • db.users.update({name : "lenny linux"}, {$pull : { computers : { name : "computer2" } }}, false, false) to remove all elements from the array computers that have name 'computer2'.

Sign up to request clarification or add additional context in comments.

Comments

1

When reaching into an array with objects (named elements), you want to use the dot notation to reach into the array.

db.myColl.find({'computers.name':'computer'});

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

as for removing items from an array, you want to look at the $pop and $pull update functions

http://www.mongodb.org/display/DOCS/Updating

2 Comments

Im sorry but I dont get it, really. How should db.myCol.find() work? I even dont know whats there in an array. I cant write find(computers, name) because I dont know the name(s) of the computers inside the array. Thats why I would like to read the whole array.
Spend some time doing the [MongoDB tutorial mongodb.org/display/DOCS/Tutorial] it doesn't take long, and you'll get a much better understanding of how documents are (or can be) structured, and how to search and find what you want.
0

Since I was dealing with this problem in Java, and your code is in Java, here is the solution ... in java.

Basically when you get(key) a MongoDB array, it returns a com.mongodb.BasicDBList object that you can get an iterator for.

In my code, I query documents that look like this:

{
    "_id": ObjectID("52d60db91f3aa664410bcde5"),
    "owner": "Amy",
    "trusted": [
        "amy",
        "paul",
        "randy"
    ]
}

And when I ever need to find the trusted people of this document, I use ((BasicDBList) doc.get("trusted")).listIterator();

        DBObject doc = collection.findOne(new BasicDBObject("owner", "Amy"))
        ListIterator<Object> trustedList = ((BasicDBList) doc.get("trusted")).listIterator();

        while(trustedList.hasNext()){
            Object nextItem = trustedList.next();
            System.out.println(nextItem.getClass()); // String
            // Here I handle what to do to each name.
            // I could add them to an ArrayList<String> if I needed
            updateTrustee((String)nextItem);
        }

I came to this solution using a few System.out.println(Object.getClass())s to know what classes I needed to cast.

Comments

0

The question he is asking is how does one return ALL the elements found in an array stored in a Mongo collection without knowing precisely how many or what these elements might be. You are not performing a query against a known value, rather you are simply asking for a dump of what is in the Mongo array. For example, if your Mongo array name is "colors", simply do the following:

@colors = @{$record->{colors}};

Now you have all the colors in a Perl array for you to play with.

Enjoy!

Comments

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.