相关文章推荐
飘逸的饭卡  ·  进程监控工具supervisor ...·  2 周前    · 
瘦瘦的伤痕  ·  [mongodb] ...·  5 天前    · 
朝气蓬勃的针织衫  ·  python socket ...·  4 月前    · 
霸气的弓箭  ·  c# 等待thread结束-掘金·  10 月前    · 
讲道义的馒头  ·  什么是 ...·  1 年前    · 
博学的领带  ·  Qt ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have a collection of documents in which some documents have filed atd and others have etd inside a nested field voyage_details , for example:

"_id" : ObjectId("..."), "voyage_details" : { "atd" : "15-Mar-21" "_id" : ObjectId("..."), "voyage_details" : { "etd" : "15-Mar-21"

Now, I want to write a mongo aggregation query where I create a new field on the basis of a condition where if a document has the key atd in it then I want to add the value of key atd in that new field and if that key is not present in the document then add the value of key etd in that new field.

I have written an aggregate query like this to add a new field on the basis of atd or etd whichever of the both is present inside the voyage_details object:

"$addFields": { "sailing_date": { "$cond": { "if": { "voyage_details.atd": { "$exists": True } }, "then": "$voyage_details.atd", "else": "$voyage_details.etd"

Can anyone guide me in writing the correct query to add a new field in my mongo aggregation, so that I can use atd or etd whichever of the both fields present inside the voyage_details section.

"$addFields": { "sailing_date": { "$ifNull": ["$voyage_details.atd", "$voyage_details.etd"]

Output:

/* 1 createdAt:3/15/2021, 3:36:19 PM*/
    "_id" : ObjectId("604f319b9ee8b82dd8cd9f3f"),
    "voyage_details" : {
        "atd" : "15-Mar-21"
    "sailing_date" : "15-Mar-21"
/* 2 createdAt:3/15/2021, 3:36:19 PM*/
    "_id" : ObjectId("604f319b9ee8b82dd8cd9f40"),
    "voyage_details" : {
        "etd" : "15-Mar-21"
    "sailing_date" : "15-Mar-21"
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.