Get document from MongoDB containing all fields but only includes the first element of an array field

48 Views Asked by At

Consider a MongoDB collection with documents as follows:

[{
    "_id": "123",
    "name": "Bob",
    "age": 23,
    "properties": ["a", "b", "c"]
},
{
    "_id": "345",
    "name": "John",
    "age": 24,
    "properties": ["r", "s", "t"]   
},
...]

I was wondering if there was a way in MongoDB to get the document corresponding to a particular id (example 123 - Bob) and get all the fields in the document. But for the properties field, I want to return and delete the first item in the list (like popping from a list).
The returned document should look like this:
{
    "_id": "123",
    "name": "Bob",
    "age": 23,
    "properties": ["a"] (or better "property": "a")
}

Is it possible to get the same using only one query to the database instead of two or three?
I am using the Java library but an answer even in MongoDBShell format will do.

0

There are 0 best solutions below