Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

mongodb - Mongo projection for only field and value

I have large documents and I want to project them with only field and value.

It goes like this;

{"p":{"s":{"status":"b"},"m":{"pd":{"tt":{"bi":"2","psi":"4","ircsi":true}},"mi":"TT","et":"2020-09-07T14:34:00+03:00"}}}
{"p":{"s":{"status":"b"},"m":{"pd":{"tt":{"bi":"20","psi":"1","ircsi":true}},"mi":"TT","et":"2020-12-29T08:28:06+03:00"}}}
.........

Is there any way for its to look like this;

{"status":"b","bi":"2","psi":"4","ircsi":true,"mi":"TT","et":"2020-09-07T14:34:00+03:00"}}}
{"status":"b","bi":"20","psi":"1","ircsi":true,"mi":"TT","et":"2020-09-07T14:34:00+03:00"}}}
.........

And my query is like this;

db.s.aggregate([{
    "$match": { 
        "p.m.etm": {
            "$gt": 1585688401000,
            "$lt": 1610565947499
        },
        "p.m.mi":"TT"
    }
},
{
    "$project": {
        "p.m.pd.tt.bi": 1,
        "p.m.pd.tt.psi": 1,
        "p.m.pd.tt.ircsi": 1,
        "p.m.mi":1,
        "p.s.status":1,
        "p.m.et":1,
        "_id": 0
    }
}],
{
    "allowDiskUse": true
});

What should I change to reach what I need ?

question from:https://stackoverflow.com/questions/65846925/mongo-projection-for-only-field-and-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use $project to create new fields. (I just remove $match for easiness)

db.collection.aggregate([
  {
    "$project": {
      "bi": "$p.m.pd.tt.bi",
      "psi": "$p.m.pd.tt.psi",
      "ircsi": "$p.m.pd.tt.ircsi",
      "mi": "$p.m.mi",
      "status": "$p.s.status",
      "et": "$p.m.et",
      "_id": 0
    }
  }
])

Working Mongo playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...