0

I have the following documents

{"_id": "1", "posts": [{"text": "all day long I dream about", "datetime": "123"}, {"text": "all day long ", "datetime": "321"}]}
{"_id": "1", "posts": [{"text": "all day long I dream about", "datetime": "123"}, {"text": "all day long ", "datetime": "8888"}, {"text": "I became very hungry after watching this movie...", "datetime": "8885"}]}

I wish to concatenate the text fields into a new field and the datetime field into a new field while also joining the arrays elements into a string in a way that the new field will be as follows

{"_id": "1", "text": "all day long I dream about, all day long ", "datetime": "123, 321"}
{"_id": "1", "text": "all day long I dream about, all day long ,I became very hungry after watching this movie... ", "datetime": "123, 8888, 8885"}

What's the best way of doing that directly on Mongodb server? Is there such way?

1 Answer 1

1

Query

  • reduce on posts starting with null (same code 2x)
  • if not null (concat all_string ", " current_string)
  • else current_string (this happens only for the first string)

*that check if not null is only for the first string, to not have something like ", string1, string2 ...." we do this to avoid add , to the first string
*you could do it with 1 reduce also, but code would be more complicated

Test code here

aggregate(
[{"$set":
  {"text":
   {"$reduce":
    {"input":"$posts",
     "initialValue":null,
     "in":
     {"$cond":
      ["$$value", {"$concat":["$$value", ", ", "$$this.text"]},
       "$$this.text"]}}}}},
 {"$set":
  {"datetime":
   {"$reduce":
    {"input":"$posts",
     "initialValue":null,
     "in":
     {"$cond":
      ["$$value", {"$concat":["$$value", ", ", "$$this.datetime"]},
       "$$this.datetime"]}}}}}
 {"$unset":["posts"]}])
Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly and you explanation is blessed. Thank you.
Let's say I want to create a new string of 'datetime' even when all the values are null, for example - "null, null, null..." How would I do that?
i think you need this , it uses one variable, if datetime is null, then it is as it it was "null" , else has the normal datetime value.
You are a magician. Thank you so much, you helped me a lot.

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.