简体   繁体   中英

alias in mongo db

I've started to fiddle with mongo db and came up with a question. Say, I have an object (POJO) with an id field (say, named 'ID') that I would like to represent in JSON and store/load in/from Mongo DB. As far as I understood any object always has _id field (with underscore, lowercased). What I would like to do is: during the query I would like the mongo db to return me my JSON with field ID instead of _id. In SQL I would use something like

SELECT _id as ID ...

My question is whether its possible to do this in mongo db, and if it is, the Java based Example will be really appreciated :)

I understand that its possible to iterate over the records and substitute the _id with ID manually but I don't want this O(n) loop. I also don't really want to duplicate the lines and store both "id" and "_id" So I'm looking for solution at the level of query or maybe Java Driver.

Thanks in advance and have a nice day

Mongodb doesnt use SQL , its more like Object Query Language and Collections.

what you can try is , some thing similar to below code using Mongo Java Driver

Pojo obj = new PojoInstance();
obj.setId(id);
db.yourdb.find(obj);

I've end up using the following approach in the Java Driver:

DBCursor cursor = runSomeQuery();
try {
        while(cursor.hasNext()) {
            DBObject dbObject  = cursor.next();
            ObjectId id = (ObjectId) dbObject.get("_id");
            dbObject.removeField("_id");
            dbObject.put("ID", id.toString());
            System.out.println(dbObject);
        }

    }   finally {
        cursor.close();
    }

I was wondering whether this is the best solution or I have other better options Mark

Here's an example of what I am doing in Javascript. It may be helpful to you. In my case I am removing the _id field and aliasing the two very nested fields to display simpler names.

db.players.aggregate([
  { $match: { accountId: '12345'}},
  { $project: {
    "_id": 0,
    "id": "$id",
    "masterVersion": "$branches.master.configuration.player.template.version",
    "previewVersion": "$branches.preview.configuration.player.template.version"
    }
  }
])

I hope you find this helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM