0

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.

4
  • Probably, you just need one $addFields like this Commented Nov 17, 2022 at 16:27
  • @ray Thank you for the reply. I had looked at aggregation before, but wouldn't this example query you've written fetch all the properties at the start and then splice after? I hadn't mentioned this earlier in my question but I am trying to not fetch all the properties at the start as the array is very long and I can save on network if I only fetch the first element in the array. Commented Nov 18, 2022 at 20:35
  • Not sure what you mean by fetch all the properties. You send the query/aggregation pipeline to the db and it would process the query at its end and return only your required first element to you. And in practice, you cannot have very long array as MongoDB document is limited to be max of 16MB Commented Nov 18, 2022 at 20:55
  • @ray My understanding was wrong. I am still fairly new to MongoDB and I thought aggregation happens client side. Thank you for clearing that up. Just for bettering my understanding, in the query you've written out, does MongoDB first fetch the matched document, store it in a temporary space, and then perform the next command on it? Commented Nov 19, 2022 at 7:23

0

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.