2016-11-11 6 views
1

백엔드에서는 go lang을 사용하고 데이터베이스는 mongoDB를 사용합니다. 나는 임베디드 배열에 삽입 된 마지막 문서를 찾으려고 노력 중이므로 인덱스를 모르는 상태에서 마지막 배열 인덱스의 문서를 검색 할 수 있습니다. 이제 직원의 모든 문서를 가져 와서 마지막 인덱스를 찾습니다. 오버로드와 같습니다. 내 RAM 전 직원의 기록 1000를 검색하고 배열의 마지막 인덱스를 발견하기 전에 램에 저장해야하므로 내 구조체 난 내 응용 프로그램에서 어떻게 여기mongodb에서 배열의 마지막 색인을 찾으십시오

type (
     Employee struct { 
      Name    string 
      Password   string 
      EmpId    string 
      EmailAddress  string 
      Position   string 
      Gender    string 
      Nationality  string 
      Department   string 
      MaritalStatus  string 
      Approvedby   string 
      JoinDate   time.Time 
      ConfirmationDate time.Time 
      EndDate   time.Time 
      Leave    []*LeaveInfo 
     } 
     LeaveInfo struct { 
      Total  float64 
      Id   int 
      Days   float64 
      From  time.Time 
      To   time.Time 
      Status  string 
      Certificate []*CertificateInfo 
     } 
     CertificateInfo struct { 
      FileName string 
      FileType string 
      FileSize int 

     } 

되는 다음과 같다

My code is follows 

    employee := Employee{} 
    err = c.Find(bson.M{ 
        "empid": "1234" 
       }).One(&result) 
    if err != nil { 
      log.Fatal(err) 
    } 
      name:=result.Name   
      lastindex:= result.LeaveInfo[len(result.LeaveInfo)-1].Id 

내가 알 수 있듯이 전체 직원 데이터를 검색 한 다음 마지막 문서의 ID를 찾습니다.

새로 추가 된 코드
This code is based on your example 

    var result bson.M 

    query := bson.M{"empid": "1234"} // gets the employee you are interested in 
    match := bson.M{"$match": query} // Set up the match part of the pipeline 
    unwind := bson.M{"$unwind": "$leave"} // sets up the leave field to be unwound 

    pipeline := []bson.M{match, unwind,{ 
    "$project":bson.M{ 
      "ID":bson.M{ 
       "$slice": []interface{}{"$leave.id", -1}, 
     } 
     } 


    iter := postCollection.Pipe(pipeline).Iter() 
    for iter.Next(&result) { 
     fmt.Printf("%+v\n", result) 
    } 
    iter.Close() 

.. 감사합니다 ... this.Appreciate 어떤 help.Please을 할 수있는 방법 어

이 코드는 나에게 (542 개) 문서와 같은 동일한 문서의 많은을 제공 나누었다 모든 문서가 동일합니다 ...

답변

1

$ 슬라이스가있는 Mongo의 버전을 실행중인 경우 2.4에서 소개되었으므로 프로젝트와 같은 Select 기능을 추가하여 찾기에서 사용할 수 있습니다 .

err = c.Find(bson.M{"empid": "1234"}).Select(bson.M{"name": 1, "leave": bson.M{"$slice": -1}}).One(&result) // result is an Employee struct 

그렇지 않으면 집계가 친구입니다. 파이프 라인을 사용하고 Employee Leave 필드를 푸는 것이 필요합니다.

은 몇 가지 간단한 단계가 있습니다 :

1) 휴가 필드가 아니라 LeaveInfos의 조각보다 하나의 LeaveInfo로 정의하여 직원 기록에 근거 결과 기록을 정의, 예를 들어

EmployeeResult struct { 
    Name string `bson:"name"` 
    Leave LeaveInfo `bson:"leave"` 
} 

bson 태그를 Employee 구조체의 LeaveInfo 태그와 동일한 이름으로 만드는 것을 잊지 마십시오.

2) 다음 단계의 부부와 함께 파이프 라인을 만들 :

query := bson.M{"empid": "1234"} // gets the employee you are interested in 
match := bson.M{"$match": query} // Set up the match part of the pipeline 
unwind := bson.M{"$unwind": "$leave"} // sets up the leave field to be unwound 
pipeline := []bson.M{match, unwind} // the pipeline you are passing to pipe. I like to split the parts of the pipe call up for clarity and ease of later modification 

3) 매개 변수로 파이프 라인 파이프에 전화를 한 후 ITER 결과 이상이 한 번에 당신에게 한 LeaveInfo를 제공해야

var (
    result EmployeeResult 
) 
iter := postCollection.Pipe(pipeline).Iter() 
for iter.Next(&result) { 
    fmt.Printf("%+v\n", result) 
} 
iter.Close() 

4) 루프의 끝에서 결과는 목록의 마지막 항목을 갖거나 아무것도 읽지 않으면 비어있게됩니다.

+0

감사합니다 user1638680 ..... mongodb에 다른 인덱스가 있습니다. 최소 인덱스를 찾는 데 도움이됩니다.이 코드는 확실히 내 코드보다 낫지 만, 1000 개의 레코드를 남겨두고 싶지는 않습니다. 우리가 방금 배열의 두 가지 특성 만 검색하는 경우에도 모든 요청에 ​​대해 램. 감사합니다 ... 다시 한번 당신의 도움에 감사드립니다. –

+0

Mongo 3.2에서는 $ slice를 Mongo 쉘의 음수와 함께 사용할 수 있습니다. 예 : – dgm

+0

죄송합니다. Mongo 쉘을 사용하면 db.c.find ({ "empid": "1234"}, { "leave : : {$ slice : -1}})와 같은 쿼리를 실행하고 배열의 마지막 항목을 얻을 수 있습니다. 나는 훑어 보았고 Go에서 $ slice를 사용하는 예제를 찾지 못했습니다. – dgm